如果我有:
def f(x):
def g(y):
return x + y
return g
f2 = f(2)
有没有办法找到 f2
将使用的 x
绑定(bind)?我看了inspect
但无法确定某些 frame
内容是否适用。换句话说,我可以在下面定义一个 closed_vars()
吗:
def closed_vars(anF):
... return ...
assert closedVars(f2) == {'x': 2}
最佳答案
您不必在此处使用 inspect
模块。
>>> dict(zip(f2.func_code.co_freevars, (c.cell_contents for c in f2.func_closure)))
{'x': 2}
适用于 Python 2.7
关于python - 在 Python 中反射(reflect)/检查封闭变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19416876/