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()
xis neither a global nor a local variable. You'd have to inspect the stack frame. Honestly, there is almost certainly no reason to do this. What are you actually trying to accomplish? IOW, you can probably accomplish this, but you probably don't really want to.xis not a local or a global variable in either of the two definitions, for the first def to work, x needs to be defined in a global scope, for the second def to work, x needs to be defined inside g