Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #49537
| References | <694830e3-080c-4e66-90e2-6cbab53be071@googlegroups.com> |
|---|---|
| Date | 2013-07-01 04:32 -0500 |
| Subject | Re: settrace doesn't trace builtin functions |
| From | Skip Montanaro <skip@pobox.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.4058.1372671160.3114.python-list@python.org> (permalink) |
> 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
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
settrace doesn't trace builtin functions skunkwerk <skunkwerk@gmail.com> - 2013-06-30 19:11 -0700 Re: settrace doesn't trace builtin functions Skip Montanaro <skip@pobox.com> - 2013-07-01 04:32 -0500
csiph-web