在Python中反映/检查封闭变量

Des*_*Des 9 python closures

如果我有:

def f(x):
  def g(y):
    return x + y
  return g

f2 = f(2)
Run Code Online (Sandbox Code Playgroud)

有没有办法找到f2将使用的'x'绑定?我看了检查,但无法判断是否有一些'框架'的东西适用.换句话说,我可以在下面定义一个closedVars():

def closed_vars(anF):
    ... return ...

assert closedVars(f2) == {'x': 2}
Run Code Online (Sandbox Code Playgroud)

Leo*_*o.Z 7

您不必在inspect此处使用该模块.

>>> dict(zip(f2.func_code.co_freevars, (c.cell_contents for c in f2.func_closure)))
{'x': 2}
Run Code Online (Sandbox Code Playgroud)

适用于Python 2.7

  • 在Python 3中,使用``__ code __.co_freevars``,``_closure__``和``cell_contents`` (2认同)

Cla*_*diu 5

您可以通过签出获取单元格内容f.func_closure(在Python 2.7.5中有效):

>>> def f(x):
...   def g(y):
...     return x + y
...   return g
... 
>>> f2 = f(2)
>>> [cell.cell_contents for cell in f2.func_closure]
[2]
Run Code Online (Sandbox Code Playgroud)

Python 3.3具有以下inspect.getclosurevars功能:

获取Python函数或方法func中的外部名称引用到其当前值的映射。ClosureVars(nonlocals, globals, builtins, unbound)返回一个命名的元组。nonlocals将引用的名称映射到词法闭包变量,将全局变量映射到函数的模块全局变量,并将内建函数映射到从函数主体可见的内建函数。unbound是在函数中引用的一组名称,这些名称在给定当前模块的globals和buildins的情况下根本无法解析。

我不确定是否可以在Python 3.3之前获得封闭变量名称。