[Python-Dev] Stack frames
M.-A. Lemburg
mal@lemburg.com
Fri, 01 Aug 2003 15:06:06 +0200
I'm currently developing an application that needs to execute
code from a library in a way that gives each call into that
system access to a set of call-specific variables.
The problem is that I can't change the library all that much,
e.g. add some context parameter to all calls, so I have to use
some other technique for accessing the call-specific variables.
I've come up with a trick that uses Python call stacks which
works quite well. My only concern is whether this technique will
continue to work in future versions of Python. Here's the
helper I'm using:
import sys
def acquire_from_call_stack(varname):
# Start from the caller of the function calling this helper
frame = sys._getframe(2)
while frame is not None:
if frame.f_locals.has_key(varname):
value = frame.f_locals[varname]
frame = None
return value
frame = frame.f_back
raise AttributeError, varname
Any idea as to what might happen to stack frames in the
future ?
--
Marc-Andre Lemburg
eGenix.com
Professional Python Software directly from the Source (#1, Aug 01 2003)
>>> Python/Zope Products & Consulting ... http://www.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/
________________________________________________________________________