Globally override built-in print function?

Dave W. evadeflow at gmail.com
Fri Apr 16 12:50:45 EDT 2010


>>>     old_print = __builtins__.print
>>>     __builtins__.print = printhook
>>>     yield
>>>     __builtins__.print = old_print
>
>> I'm pretty sure this is semantically equivalent to my original
>> code, but I gave it a try anyway.
>
> Not at all. Declaring "global print" then assigning to "print"
> simply changes what the module's "print" variable refers to. Other
> modules are unaffected.  "Global" variables aren't truly global;
> they are actually local to the module.  You need to replace it in
> the __builtins__ because that's where everyone else gets it.
>
> > FWIW, it doesn't work, either. :-}
>
> Right. Lie answered why. I didn't pay attention and thought you
> were already using Python 3.

Thanks, Robert and Lie for the considered and informative responses.
Getting feedback like this from people who really understand
Python's internals is invaluable.  Sounds like redirecting
stdout/stderr is the way to go.  (Especially given that they're not
the 'real' stdout/stderr---that was news to me!)

[xref "Suppress output to stdout/stderr in InteractiveInterpreter"]



More information about the Python-list mailing list