Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError on CodeType creation in Python 3

I'm trying to create a new CodeType, the following code runs just fine in Python 2.7, but in Python 3.2 I get an error:

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)

Usage:

return newCode(co_code = code, co_stacksize = size, co_consts = consts)

The debug line proves that I'm sending in an int as co_stacksize...what changed in Python 3 to make this not work?

Edit: Here's the error (don't know why I forgot that before):

TypeError: an integer is required

like image 263
Timothy Baldridge Avatar asked Oct 09 '22 03:10

Timothy Baldridge


1 Answers

On Python 3, the second argument to CodeType is the number of keyword-only arguments, co_kwonlyargcount. It's an addition, so all the later arguments will be shifted by one position.

I dug this up from IPython's codebase, in a utility module which allows pickling code objects: https://github.com/ipython/ipython/blob/master/IPython/utils/codeutil.py#L32

like image 167
Thomas K Avatar answered Oct 17 '22 06:10

Thomas K