Misleading wikipedia article on Python 3?

Ricardo Aráoz ricaraoz at gmail.com
Thu Aug 9 13:06:50 EDT 2007


Evan Klitzke wrote:
> On 8/8/07, greg <greg at cosc.canterbury.ac.nz> wrote:
>> Istvan Albert wrote:
>>> A solution would be writing the code with a logging function to begin
>>> with, alas many times that is out of one's hand.
>> If the code has been written with calls to a builtin
>> print function, the situation isn't much better. You
>> could monkeypatch the print function, but that's
>> probably worse than swapping sys.stdout.
> 
> You can easily modify print in a safe way. Here's an example, that
> will work in any recent version of Python:
> 
> import sys
> 
> def print_(s):
>     print s
> 
> def logger(method):
>     def wrapper(s):
>         sys.stderr.write('Logging: %s\n' % s)
>         method(s)
>     return wrapper
> 
> print_ = logger(print_)
> 
> print_('hello')
> 
> 
> Running this code will do a regular print of 'hello', as well as
> "logging" it to stderr. As a function, you can convert print wholesale
> to another logging function, or wrap it transparently like this to
> provide additional logging functionality. What do you find wrong with
> this sort of "monkeypatching"?
> 

foolish question maybe.
Why wouldn't you do it this way ?

def print_(s):
    print s

def logger(m):
    sys.stderr.write('Logging: %s\n' % m)
    method(m)

print_ = logger(print_)

print_('hello')







More information about the Python-list mailing list