Re: Misleading wikipedia article on Python 3?



On 8/8/07, greg <greg@xxxxxxxxxxxxxxxxxxxxx> 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"?

--
Evan Klitzke <evan@xxxxxxxx>
.



Relevant Pages

  • Re: Misleading wikipedia article on Python 3?
    ... alas many times that is out of one's hand. ... If the code has been written with calls to a builtin ... def logger: ... to another logging function, or wrap it transparently like this to ...
    (comp.lang.python)
  • Re: Accessing overridden __builtin__s?
    ... no longer refers to the builtin open(), ... no longer refers to the builtin's open, ... self.fname = fname ... def close: ...
    (comp.lang.python)
  • Re: Beginner question: use function to read text file
    ... Luke wrote: ... builtin function of the same name used to open files. ... variable in a def, then ANYWHERE in that def, that name refers to the ... import fileloader ...
    (comp.lang.python)
  • Proper way of handling "plug-in" methods
    ... def builtinMethod: return someOutput ... #References all the methods, both builtin and custom ... both builtin and custom scripts since it is the same logic for me. ...
    (comp.lang.python)
  • Re: Accessing overridden __builtin__s?
    ... The convention is to use all_lowercase names for modules, and CamelCase ... def open: ... This shadows the builtin open() function. ...
    (comp.lang.python)