Why does Python3.11 code construction modify inputted co_code?

94 Views Asked by At

I'm trying to create a code object (Python 3.11) with modified co_code to another function, but I notice that the CodeType constructor seems to modify the inputted co_code.

For example:

import types
import random

def f(a):
    a = a + 1
    return a

codeobj = f.__code__

new_co_code = bytes([random.randint(0, 255) for _ in range(24)])
new_code = types.CodeType(
    codeobj.co_argcount,
    codeobj.co_posonlyargcount,  
    codeobj.co_kwonlyargcount,
    codeobj.co_nlocals,
    codeobj.co_stacksize,
    codeobj.co_flags,
    new_co_code,
    codeobj.co_consts,
    codeobj.co_names,
    codeobj.co_varnames,
    codeobj.co_filename,
    codeobj.co_name,
    codeobj.co_qualname,
    codeobj.co_firstlineno,
    codeobj.co_lnotab,
    codeobj.co_exceptiontable,
)

print(new_co_code)
print(new_code.co_code)

# this assertion will generally fail
assert new_co_code == new_code.co_code
"""
example output:

b'\xe6\x8f\xdb\xc8\xb8\xb86\xe6&a\x18\xfb\x11&\xbc\xce\xc0A\xedjg\x8a\xa4G'
b'\x00\x8f\x00\xc8\x00\xb86\xe6\x8ca\xab\xfb\x00\x00\x00\x00\x00\x00\x00\x00g\x8a\xa4G'
"""

I would assume the newly created code objects co_code would be the same as the parameter I input, but there seems to be some modification done before hand. The resulting code object if you call it will segfault anyways so I dont understand why any modification is needed.

Why does it modify it, and where can I see more documentation about it, the only documentation I see about CodeType is that its just defined as f.__code__ in types.py.

0

There are 0 best solutions below