Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中调用代码对象_Python_Unit Testing_Introspection - Fatal编程技术网

如何在Python中调用代码对象

如何在Python中调用代码对象,python,unit-testing,introspection,Python,Unit Testing,Introspection,当我得到一个代码对象(通过像.func\u code这样的内部结构)时,有没有方法调用这段代码?简单地称它不起作用: def f(): pass f.func_code() 导致 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'code' object is not callable <code object g at 0x7f123991

当我得到一个代码对象(通过像
.func\u code
这样的内部结构)时,有没有方法调用这段代码?简单地称它不起作用:

def f(): pass

f.func_code()
导致

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'code' object is not callable
<code object g at 0x7f123991b930, file "<stdin>", line 2>
导致

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'code' object is not callable
<code object g at 0x7f123991b930, file "<stdin>", line 2>
<0x7f123991b930处的代码对象g,文件“stdin”,第2行>
当然,这段代码仍然需要上下文等,但这不是我的问题。

可以
eval()
exec
执行它们

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

您可以
eval
exec
它们。您可以创建一个新函数并为其分配
func\u code
。请参阅中的
add_self()
函数,该函数显示如何执行类似操作。@vaultah这正是我的解决方案!你愿意把它写在A中,这样我就可以接受它,只是为了正确地关闭这个Q吗?不,但是你可以自己发布它。:)@如果您可以获得
函数
类型(
类型.函数类型
),并使用它来构造新的函数对象。有关参数的说明,请参见
types.FunctionType.\uuuu doc\uuu