如何在Python中调用代码对象

2024-06-15 04:36:50 发布

您现在位置:Python中文网/ 问答频道 /正文

当我获得一个代码对象(通过.func_code)时,有没有任何方法可以调用这段代码?简单地调用它是行不通的:

def f(): pass

f.func_code()

结果

^{pr2}$

当您想对嵌套函数进行单元测试时,这会很方便:

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>

当然,这段代码还需要上下文等等,但这不是我的问题。在


Tags: 对象方法函数代码returnobjectdefcode
1条回答
网友
1楼 · 发布于 2024-06-15 04:36:50

你可以eval()或{}它们。在

如果它们有自由变量(例如,对于其外部函数在嵌套函数之前定义了局部变量的嵌套函数代码),这是不可能直接实现的(在本例中,eval或{}引发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

相关问题 更多 >