I was wondering, is there a function in Python that returns a dict object that contains nonlocal variables used in enclosing functions? Like vars()
or locals()
for local variables or globals()
for global ones.
Update:
As thebjorn noted, nonlocal variables that are actually used in the nested function are included in the local
list. On 3.2.3 the following code
>>> def func1():
... x=33
... def func2():
... # Without the next line prints {}
... print(x)
... print(locals())
... func2()
...
>>> func1()
returns {'x': 33}
.
There is no builtin nonlocals()
, but you can create one yourself:
def nonlocals():
import inspect
stack = inspect.stack()
if len(stack) < 3: return {}
f = stack[2][0]
res = {}
while f.f_back:
res.update({k:v for k,v in f.f_locals.items() if k not in res})
f = f.f_back
return res
if i run it on your program I get:
{'func2': <function func1.<locals>.func2 at 0x0000000002A03510>, 'x': 33}
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