Injecting code into a function

Ron radam2 at tampabay.rr.com
Mon Apr 25 09:31:30 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

I'd like to know this as well.  :)

I think you will have to modify the function func in some way to get 
locals when it exits.

def func():
     x = 20
     y = 40
     func.locals = locals()   # inserted line

func()
print func.locals


On a related note, I'd like to know how to import locals into a function.

Cheers,
Ron














More information about the Python-list mailing list