python执行过程中加载代码_如何在Python中调用代码对象

When I get hold of a code object (via internals like .func_code), is there any way of calling this piece of code? Simply calling it does not work:

def f(): pass

f.func_code()

results in

Traceback (most recent call last):

File "", line 1, in

TypeError: 'code' object is not callable

This can come in handy when you like to unit-test a nested function:

def f():

def g():

return 3

f.x = g

return g() + 1

f.func_code.co_consts[1]

results in

", line 2>

Of course, this piece of code still needs a context etc. but that's not my question here.

解决方案

One can eval() or exec them.

If they have free variables (e. g. for the code of nested functions whose outer function has local variables defined before the nested function), this is not directly possible (eval or exec raise a TypeError in this case).

Also, passing arguments to the code is not directly possible.

But one can create a wrapping function for the given code on-the-fly. This function can normally be called (using f(…)), passing arguments in the usual way. This is done using types.FunctionType. To achieve references to free variables, one must use a trick in order to get the correct data type as Python expects it. See the code below for an example:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值