Injecting code into a function
George Sakkis
gsakkis at rutgers.edu
Mon Apr 25 06:32:38 EDT 2005
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
More information about the Python-list
mailing list