Rationale for read-only property of co_code

Arnaud Delobelle arnodel at googlemail.com
Thu Apr 3 16:00:32 CEST 2008


On Apr 3, 11:10 am, João Neves <seve... at gmail.com> wrote:
> On Apr 3, 4:43 am, Scott David Daniels <Scott.Dani... at Acm.Org> wrote:
>
> > Nope:  If you change the code in-place, the whole stack's references
> > to where they were running would need to get updated to corresponding
> > locations in the new code.  _That_ is a lot of work.
>
> Ah, there it is. Now I get it, it makes perfect sense.
> Looks like I'll have to stick to the usual mechanisms!
> Thanks everyone!
>
> ---
> João Neves

FWIW, when I need to 'modify' a code object / function object I use
the following functions:

from new import code, function

code_args = (
    'argcount', 'nlocals', 'stacksize', 'flags', 'code',
    'consts', 'names', 'varnames', 'filename', 'name',
    'firstlineno', 'lnotab', 'freevars', 'cellvars'
    )

function_args = ('code', 'globals', 'name', 'defaults', 'closure')

def copy_code(code_obj, **kwargs):
    "Return a copy of a code object, maybe changing some attributes"
    for arg in code_args:
        if not kwargs.has_key(arg):
            kwargs[arg] = getattr(code_obj, 'co_%s' % arg)
    return code(*map(kwargs.__getitem__, code_args))

def copy_function(func_obj, **kwargs):
    "Return a copy of a function object, maybe changing some
attributes)"
    for arg in function_args:
        if not kwargs.has_key(arg):
            kwargs[arg] = getattr(func_obj, 'func_%s' % arg)
    return function(*map(kwargs.__getitem__, function_args))

# E.g. to change the code object of a function:

f = copy_function(f, code=new_code_object)




More information about the Python-list mailing list