我正在尝试创建一个新的 CodeType,以下代码在 Python 2.7 中运行良好,但在 Python 3.2 中出现错误:
def newCode(co_argcount = 0, co_nlocals = 0, co_stacksize = 0, co_flags = 0x0000,
co_code = bytes(), co_consts = (), co_names = (), co_varnames = (),
filename = "<string>", name = "", firstlineno = 0, co_lnotab = bytes(),
co_freevars = (), co_cellvars = ()):
"""wrapper for CodeType so that we can remember the synatax"""
print(type(co_stacksize))
return types.CodeType(co_argcount, co_nlocals, co_stacksize,
co_flags, co_code, co_consts, co_names, co_varnames,
filename, name, firstlineno, co_lnotab, co_freevars, co_cellvars)
用法:
return newCode(co_code = code, co_stacksize = size, co_consts = consts)
调试行证明我将 int 作为 co_stacksize 发送......在 Python 3 中发生了什么变化以使其不起作用?
编辑:
这是错误(不知道为什么我之前忘记了):
TypeError:需要一个整数
最佳答案
在 Python 3 上,CodeType
的第二个参数是仅关键字参数的数量,co_kwonlyargcount
.这是一个加法,所以后面的所有参数都将移动一个位置。
我从 IPython 的代码库中挖掘了这个,在一个允许腌制代码对象的实用程序模块中:
https://github.com/ipython/ipython/blob/master/IPython/utils/codeutil.py#L32
关于python - 在 Python 3 中创建 CodeType 时出现 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10116650/