python - 在 Python 中反射(reflect)/检查封闭变量

标签 python closures

如果我有:

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/

相关文章:

swift - 'Int' 与闭包中的 'UInt8' 不同

javascript - JavaScript闭包如何工作?

python - Pygame 平台游戏 - 随机生成敌人

python - ElementTree 中 findall 函数的无法解释的行为

python - 在 Python 中,是否可以使用同一个装饰器来装饰类方法和非类方法?

javascript - 为什么使用 IFFE 闭包而不是常规闭包?

python - 如何从 Python3 中的像素值列表创建图像?

Python BeautifulSoup 每页仅获取 1 项

python - 抓取互动网站

multithreading - 一个 Rust 闭包可以被多个线程使用吗?