python的代码类型_关于类型.代码类型()python调用?

我去拿找到的代码here,并删除了不推荐使用的“new”模块的依赖项。在import types, copy_reg

def code_ctor(*args):

# delegate to new.code the construction of a new code object

return types.CodeType(*args)

def reduce_code(co):

# a reductor function must return a tuple with two items: first, the

# constructor function to be called to rebuild the argument object

# at a future de-serialization time; then, the tuple of arguments

# that will need to be passed to the constructor function.

if co.co_freevars or co.co_cellvars:

raise ValueError, "Sorry, cannot pickle code objects from closures"

return code_ctor, (co.co_argcount, co.co_nlocals, co.co_stacksize,

co.co_flags, co.co_code, co.co_consts, co.co_names,

co.co_varnames, co.co_filename, co.co_name, co.co_firstlineno,

co.co_lnotab)

# register the reductor to be used for pickling objects of type 'CodeType'

copy_reg.pickle(types.CodeType, reduce_code)

if __name__ == '__main__':

# example usage of our new ability to pickle code objects

import cPickle

# a function (which, inside, has a code object, of course)

def f(x): print 'Hello,', x

# serialize the function's code object to a string of bytes

pickled_code = cPickle.dumps(f.func_code)

# recover an equal code object from the string of bytes

recovered_code = cPickle.loads(pickled_code)

# build a new function around the rebuilt code object

g = types.FunctionType(recovered_code, globals( ))

# check what happens when the new function gets called

g('world')

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值