Modifying a built-in function for logging purposes
Steven D'Aprano
steve at REMOVETHIScyber.com.au
Sun May 15 07:59:01 EDT 2005
On Sat, 14 May 2005 15:14:01 -0700, qwweeeit wrote:
> Hi Greg,
> thank for your replay, but I didn't succeed in any way. You must
> consider however that I'm not a Python "expert"...
Can you post what you did and what results you got? Because Greg's trick
worked for me. See below.
> IMHO, it must be a script that change part of the interpreter, and
> substitute a new module (py) in the place of the standard one (py or
> pyc). The standard module must be saved in order to be able to undo the
> changes and go back to the normal behaviour. The problem is that I don't
> know if the built-in functions like open (or file) are written in Python
> or in C and, besides that, if they can be modified.
Why do you think it matters if they are written in Python or C or any
other language for that matter? Almost everything in Python is a
first-class object. That means you can rebind functions, methods, classes,
and any other object.
You can't rebind statements like print. But open is just an object:
py> open
<type 'file'>
py> print open("Something.txt", "r").read()
some text in a file
py>
py> save_open = open
>>> save_open
<type 'file'>
py>
py> def open(pathname, mode):
... print "The pathname is: " + pathname
... print "The mode is: " + mode
... return save_open(pathname, mode)
...
py> contents = open("Something.txt", "r").read()
The pathname is: Something.txt
The mode is: r
py> contents
'some text in a file'
> Other solutions
> which modify the source to be logged, are not solutions, because it is
> far simpler to introduce here and there print statements... Bye.
Introducing print statements is good for quick-and-dirty debugging. For
more serious work, you should investigate the debug module.
--
Steven
More information about the Python-list
mailing list