Is there a way to use something like globals()
or locals()
to access a variable defined in a parent function by name (i.e., as a string)?
Both of these examples give KeyError: 'x'
:
def f():
x = 1
def g():
print(globals()['x'])
g()
def f():
x = 1
def g():
print(locals()['x'])
g()
Yes it's possible, but you are working against Python, don't do this:
In [1]: import inspect
In [2]: def f():
...: x = 1
...: def g():
...: print(inspect.currentframe().f_back.f_locals['x'])
...: g()
...:
In [3]: f()
1
Seriously, don't. Write good code, not bad code. For all of us.
I'm not really sure about it's usefullness, but you can do this by inspecting the stack frame of the enclosing function i.e. frame at depth 1 and getting x
from the locals
dict:
In [1]: import sys
In [2]: def f():
...: x = 1
...: def g():
...: print(sys._getframe(1).f_locals['x'])
...: g()
...:
In [3]: f()
1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With