反映/检查Python中的封闭变量 [英] Reflect / Inspect closed-over variables in Python

查看:68
本文介绍了反映/检查Python中的封闭变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有:

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

f2 = f(2)

是否可以找到 f2 将使用的 x 绑定?我看着 检查 ,但无法确定某些框架是否适用。换句话说,我可以在下面定义一个 closed_vars()

Is there a way to find the x binding that f2 will use? I looked at inspect but could not tell if some of the frame stuff would apply. In other words, could I define a closed_vars() below:

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

assert closedVars(f2) == {'x': 2}


推荐答案

您不必使用检查

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

在python 2.7中工作

works in Python 2.7

这篇关于反映/检查Python中的封闭变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆