settrace doesn't trace builtin functions
Skip Montanaro
skip at pobox.com
Mon Jul 1 05:32:32 EDT 2013
> I've been using the settrace function to write a tracer for my program, which is working great except that it doesn't seem to work for built-in functions, like open('filename.txt'). This doesn't seem to be documented, so I'm not sure if I'm doing something wrong or that's the expected behavior.
I believe that's expected behavior. Stuff written in Python is
traced. C functions are not. It's been a whole lot of years since I
looked at that code though, so I might be misremembering.
> The other option I considered was monkey-patching the open function through a wrapper ... but that seemed very brittle to me.
For debugging purposes, practicality beats purity. I trust you won't
be tracing in a production environment, so fragility shouldn't be a
major concern. Monkey patching seems entirely appropriate to me.
Python 2.x:
>>> open
<built-in function open>
>>> import __builtin__
>>> open is __builtin__.open
True
>>> _open = __builtin__.open
>>> def open(name, mode=None, buffering=None):
... return _open(name, mode, buffering)
...
>>> __builtin__.open = open
>>> open is __builtin__.open
True
>>> open
<function open at 0x82afa3c>
Python 3.x:
>>> import builtins
>>> open
<built-in function open>
>>> open is builtins.open
True
>>> _open = builtins.open
>>> def open(file, mode='r', buffering=-1, encoding=None,
... errors=None, newline=None, closefd=True, opener=None):
... return _open(file, mode, buffering, encoding, errors, newline,
closefd, opener)
...
>>> _open
<built-in function open>
>>> builtins.open = open
>>> open
<function open at 0x1010c18c8>
You can, of course, do this for more builtins. Presuming you can get
a handle on a function's namespace and modify it, you should be able
to perform the same trick for most functions or methods written in C.
>>> sys._settrace = sys.settrace
>>> def settrace(*args, **kwds):
... return sys._settrace(*args, **kwds)
...
>>> sys.settrace = sys._settrace
Totally untested. No warranties expressed or implied. YMMV... etc, etc
Skip
More information about the Python-list
mailing list