python - 有没有办法获得带有非局部变量的 dict 对象?

标签 python python-3.x

<分区>

我想知道,Python 中是否有一个函数返回一个包含封闭函数中使用的非局部变量的 dict 对象?像局部变量的 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}

最佳答案

没有内置的 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}

关于python - 有没有办法获得带有非局部变量的 dict 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22438219/

相关文章:

python - 检查文件中的数据是否重复 (Python)

python - 在列表字典中搜索值

使用 cron-job 将 Python 输出到文本文件

python - 如何基于 Pandas 数据框中的单列(内爆或嵌套)合并多行?

python - 计算 itertools.product() 的第 n 个结果

python - 将文本文件转换为字典

python - pyautogui 每次点击都会崩溃

python - 与pygame一起使用时如何防止pyttsx产生断断续续的语音?

python 网络抓取 - len(containers) 总是返回 0

python - 从不可变对象(immutable对象)读取时使用 multiprocessing.pool 映射时出错