Please note that the present is a fork of the recipe 577283 "Decorator to expose local variables of a function after execution" of Pietro Berkes, available at http://code.activestate.com/recipes/577283-decorator-to-expose-local-variables-of-a-function-/ , and aiming only to report the alternative implementation "persistent_locals2", whose I'm co-author with Pietro Berkes, and which was submitted together to the original recipe. Refer to the latter for an exhaustive description and discussion.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #This is fork of the recipe 577283 "Decorator to expose local variables of a function after execution"
#available at http://code.activestate.com/recipes/577283-decorator-to-expose-local-variables-of-a-function-/.
class persistent_locals2(object):
def __init__(self, func):
self._locals = {}
self.func = func
def __call__(self, *args, **kwargs):
def tracer(frame, event, arg):
if event=='return':
self._locals = frame.f_locals.copy()
# tracer is activated on next call, return or exception
sys.setprofile(tracer)
try:
# trace the function call
res = self.func(*args, **kwargs)
finally:
# disable tracer and replace with old one
sys.setprofile(None)
return res
def clear_locals(self):
self._locals = {}
@property
def locals(self):
return self._locals
|