当我掌握一个代码对象时(通过内部结构,例如.func_code
or __code__
在Python 3)中,有什么办法calling这段代码?简单地调用它是行不通的:
def f(): pass
f.func_code()
结果是
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'code' object is not callable
当您想对嵌套函数进行单元测试时,这会派上用场:
def f():
def g():
return 3
f.x = g
return g() + 1
f.func_code.co_consts[1]
结果是
<code object g at 0x7f123991b930, file "<stdin>", line 2>
当然,这段代码仍然需要上下文等,但这不是我的问题。
One can eval()
or exec
them.
如果他们有自由变量(例如,对于其外部函数具有在嵌套函数之前定义的局部变量的嵌套函数的代码),这不是直接可能的(eval
or exec
提出一个TypeError
在这种情况下)。
此外,无法直接将参数传递给代码。
但是我们可以为给定的代码即时创建一个包装函数。该函数通常可以被调用(使用f(…)
),以通常的方式传递参数。这是使用完成的types.FunctionType
。为了实现参考自由变量,必须使用一种技巧才能获得 Python 所期望的正确数据类型。请参阅下面的代码示例:
def f(v1=1):
v2 = 2
def g(v3=4):
return v1 + v2 + v3 + 8
return g() + 16
def freeVar(val):
def nested():
return val
return nested.__closure__[0]
def nested(outer, innerName, **freeVars):
if isinstance(outer, (types.FunctionType, types.MethodType)):
outer = outer.func_code
for const in outer.co_consts:
if isinstance(const, types.CodeType) and const.co_name == innerName:
return types.FunctionType(const, globals(), None, None, tuple(
freeVar(freeVars[name]) for name in const.co_freevars))
nestedG = nested(f, 'g', v1=1, v2=2)
print nestedG(4) # will print 15
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)