Python 3 - Substituting Functions For Print()
I'm trying to write a replacement for the print() function; I'd like to understand what Python 3 is doing here. Consider the following two Python 3 source files: file.py: def in_a_
Solution 1:
The name lookup is roughly builtins
shared by all modules, each module's own global
namespace, and then subsequently nested function/class namespaces. The print
function lives in builtins
, and is thus visible in all modules by default.
The assignment print = printA
in minimal.py
adds a new name print
to minimal
's global namespace. This means minimal.print
shadows builtins.print
inside the minimal
module. The change is not visible in any other module, since each has a separate module-global namespace.
To change print
across all modules, re-assign builtins.print
.
import builtins
_real_print = builtins.print
def printA(*args, **kwargs):
_real_print("A: ", end="")
_real_print(*args, **kwargs)
builtins.print = printA
Post a Comment for "Python 3 - Substituting Functions For Print()"