有没有办法获取包含非局部变量的字典对象?

6 投票
2 回答
1102 浏览
提问于 2025-04-17 22:32

我在想,Python里有没有一个函数可以返回一个字典,这个字典里包含了在外层函数中使用的非局部变量?就像 vars()locals() 用于局部变量,或者 globals() 用于全局变量一样。

更新:正如thebjorn提到的,实际上在嵌套函数中被使用的非局部变量会被包含在 local 列表中。在3.2.3版本中,以下代码

>>> def func1():
...     x=33
...     def func2():
...             # Without the next line prints {}
...             print(x)
...             print(locals())
...     func2()
... 
>>> func1()

返回 {'x': 33}

2 个回答

4

这个被接受的答案是非常错误的——f_back 返回的是调用者,而不是词法上的父作用域!

Python 是基于词法作用域的,而不是动态作用域的!

你想要的可以通过这里描述的方法来实现:这里

def nonlocals():
    import inspect
    caller = inspect.currentframe().f_back
    return {k: v for k, v in caller.f_locals.items() if k in caller.f_code.co_freevars}

请注意,这个方法只会返回在函数中实际使用的变量名,而不会返回那些存在但没有被使用的非局部变量。

4

没有内置的 nonlocals() 函数,但你可以自己创建一个:

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

如果我在你的程序上运行它,我得到:

{'func2': <function func1.<locals>.func2 at 0x0000000002A03510>, 'x': 33}

撰写回答