sys.settrace 'call' event behavior
constant.beta at gmail.com
Sat Jun 21 15:47:29 CEST 2008
I'm building a tool to trace all function calls using sys.settrace
function from the standard library. One of the awkward behaviors of
this facility is that the class definitions are reported as 'call'
events. Since I don't want to catch class definitions, only
function calls, I'm looking for a way to differentiate between those
two. So far I have only vague clues about how to do that.
At the bottom of this mail is a simple script that prints all
attributes (except for the bytecode) of the traced code. In the sample
code Bar class is defined and foo function is called after that. The
following trace output is reported:
Bar, 0, 0, (), (), (), (None,), ('__name__', '__module__', 'None'),
foo.py, 21, , 1, 66
foo, 0, 0, (), (), (), (None,), (), foo.py, 25, , 1, 67
Class definition and function call differs on four attributes. Two of
them, co_name and co_firstlineno are not very helpful. Other two are
co_names and co_flags. The latter differs only by the CO_OPTIMIZED
flag, which is for "internal use only". So we're left with
co_names, which "is a tuple containing the names used by the
bytecode". Is that helpful in distinguishing between class definitions
and function calls? Do you have any other ideas on how to tell them
Source of the sample script I used follows.
def trace(frame, event, arg):
if event == 'call':
print ', '.join(map(str, [frame.f_code.co_name,
 It is strange for me, but documented properly.
http://docs.python.org/lib/debugger-hooks.html says that call event
happens when "a function is called (or some other code block
More information about the Python-list