Injecting code into a function

Kay Schluehr kay.schluehr at gmx.net
Tue Apr 26 01:27:31 EDT 2005


Lonnie Princehouse wrote:
> I don't know of a way to get the current global trace function.  This
> could certainly cause trouble if you're trying to be compatible with
> other packages that want to use their own trace functions (like
psyco,
> or debuggers).   Does anyone know how to get the global trace?
>
> On the other hand, the local trace function is in the f_trace
attribute
> of a frame.

Oh, I overlooked this. Then the solution becomes simple:

   sys._getframe().f_trace

Test:

>>> an = Analyzer()
>>> sys.settrace(an.trace_returns)
>>> sys._getframe().f_trace
<bound method Analyzer.trace_returns of <__main__.Analyzer instance at
0x010015D0>>


> It looks like global trace functions only get the "call" event, and
are
> expected to return a local trace function that will receive "line"
and
> "return" events, so you will need a global trace in order to set
local
> traces (setting myframe.f_trace explicitly doesn't seem to do it).

I think that Your trace_returns function is actually a global trace
that returns itself and does not handle the 'call' event.

If You look at the code in the debug-module bdb.py the 'call' event
gets handled by the local trace function dispactch_call():

    def trace_dispatch(self, frame, event, arg):
        if self.quitting:
            return # None
        if event == 'line':
            return self.dispatch_line(frame)
        if event == 'call':
            return self.dispatch_call(frame, arg)
        if event == 'return':
            return self.dispatch_return(frame, arg)
        if event == 'exception':
            return self.dispatch_exception(frame, arg)
        print 'bdb.Bdb.dispatch: unknown debugging event:', `event`
        return self.trace_dispatch

Ciao,
Kay




More information about the Python-list mailing list