Injecting code into a function

Steve Holden steve at holdenweb.com
Mon Apr 25 12:45:18 EDT 2005


George Sakkis wrote:
> Is there a general way of injecting code into a function, typically
> before and/or after the existing code ? I know that for most purposes,
> an OO solution, such as the template pattern, is a cleaner way to get
> the same effect, but it's not always applicable (e.g. if you have no
> control over the design and you are given a function to start with). In
> particular, I want to get access to the function's locals() just before
> it exits, i.e. something like:
> 
> def analyzeLocals(func):
>     func_locals = {}
>     def probeFunc():
>         # insert func's code here
>         sys._getframe(1).f_locals["func_locals"].update(locals())
>     probeFunc()
>     # func_locals now contains func's locals
> 
> So, how can I add func's code in probeFunc so that the injected code
> (the update line here) is always called before the function exits ?
> That is, don't just inject it lexically in the end of the function if
> there are more than one exit points. I guess a solution will involve a
> good deal bytecode hacking, on which i know very little; if there's a
> link to a (relatively) simple HOWTO, it would be very useful.
> 
> Thanks,
> George
> 
A decorator would seem to be the sensible way to do this, assuming you 
are using Python 2.4.

def decorated(func):
     def wrapper(arg1, arg2, arg3):
         print "Arg2:", arg2
         func(arg1)
         print "Arg3:", arg3
     return wrapper

@decorated
def f1(x):
     print "F1:", x

f1('ARG1', 'ARG2', 'ARG3')

Arg2: ARG2
F1: ARG1
Arg3: ARG3

All the decorator really does is compute one function from another. 
There's been enough discussion on the list recently that I won't repeat 
the theory.

regards
  Steve
-- 
Steve Holden        +1 703 861 4237  +1 800 494 3119
Holden Web LLC             http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/




More information about the Python-list mailing list