Injecting code into a function

George Sakkis gsakkis at rutgers.edu
Mon Apr 25 15:36:44 EDT 2005


"Lonnie Princehouse" wrote:

> I expect you could combine the following with decorators as an easy
way
> to grab a function's locals just before it exits...  you could also
use
> exec or eval to execute code in the function's local namespace.
> ---------------------------------------
>
> # Try it:
>
> def trace_returns(frame, event, arg):
>   if event == 'return':
>     print "[frame locals just before return: %s]" % frame.f_locals
>   return trace_returns
>
> def foo(a, b):
>   return a + b
>
> import sys
> sys.settrace(trace_returns)
>
> foo(1,2)
>

Thanks, that's the closest to what I wanted. A minor point I didn't
quite get from the documentation is how to set a local trace instead of
a global (sys) trace. Also, there's no sys.gettrace() to return the
current tracer; is there a way around this ?

George




More information about the Python-list mailing list