【问题标题】:TypeError on CodeType creation in Python 3在 Python 3 中创建 CodeType 时出现 TypeError
【发布时间】:2012-04-12 02:32:20
【问题描述】:

我正在尝试创建一个新的 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 python-3.x


【解决方案1】:

在 Python 3 上,CodeType 的第二个参数是关键字参数的数量,co_kwonlyargcount。这是一个加法,所以后面的所有参数都会移动一个位置。

我从 IPython 的代码库中挖掘了这个,在一个允许腌制代码对象的实用模块中: https://github.com/ipython/ipython/blob/master/IPython/utils/codeutil.py#L32

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-18
    • 2018-05-03
    • 2018-07-27
    • 1970-01-01
    • 2015-03-30
    • 2018-07-02
    • 2015-01-06
    • 2021-04-01
    相关资源
    最近更新 更多