When operating code objects, do NOT directly use types.CodeType
and use pyobject.Code
instead, as constructing types.CodeType
is too complex and not compatible across multiple Python versions.
The pyobject library, which can be installed via pip install pyobject
, provides a high-level wrapper for code objects.
For example, your newCode
function can be replaced by:
from pyobject import Code
c=Code() # use default attributes to create it
# firstly define consts, size, etc.
c.co_consts=consts
c.co_stacksize=size
...
# convert it to bytecode (types.CodeType)
co=c.to_code()
# or disassembly it (equivalent to dis.dis(c.to_code()) )
c.dis()
For the documentation, please refer to the README.rst in pyobject ยท GitHub.
Note: I'm the developer of pyobject
.