Consider this example:
def outer():
s_outer = "outer\n"
def inner():
s_inner = "inner\n"
do_something()
inner()
I want the code in do_something
to be able to access the variables of the calling functions further up the call stack, in this case s_outer
and s_inner
. More generally, I want to call it from various other functions, but always execute it in their respective context and access their respective scopes (implement dynamic scoping).
I know that in Python 3.x, the nonlocal
keyword allows access to s_outer
from within inner
. Unfortunately, that only helps with do_something
if it's defined within inner
. Otherwise, inner
isn't a lexically enclosing scope (similarly, neither is outer
, unless do_something
is defined within outer
).
I figured out how to inspect stack frames with the standard library inspect
, and made a small accessor that I can call from within do_something()
like this:
def reach(name):
for f in inspect.stack():
if name in f[0].f_locals:
return f[0].f_locals[name]
return None
and then
def do_something():
print( reach("s_outer"), reach("s_inner") )
works just fine.
Can reach
be implemented more simply? How else can I solve the problem?