Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get a dict object with nonlocal variables?

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}.

like image 821
ComposM Avatar asked Mar 16 '14 14:03

ComposM


1 Answers

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}
like image 191
thebjorn Avatar answered Sep 29 '22 17:09

thebjorn