Statespressions? (Re: Draft Pep (was: Re: Let's Talk About Lambda Functions!))

Duncan Booth duncan at
Thu Aug 8 12:07:15 CEST 2002

Michael Hudson <mwh at> wrote in 
news:lkadnxog0r.fsf at

> Duncan Booth <duncan at> writes:
>> You can probably build a new code object using new.code(), but with 14 
>> arguments to be passed in I can't be bothered showing an example.
> I have this useful function lying around:
<snipped function with a lot of arguments>
> So you can go
> new_code = copy_code_with_changes(old_code, name="case a")
> pychecker complains that it has too many arguments...
> Cheers,
> M.
Oh alright, here is my take on your function, along with a genuinely 
anonymous function builder:

import new

def copy_code_with_changes(code, **kw):
    args = []

    for name in ('argcount','nlocals','stacksize','flags',
            args.append(kw.get(name, getattr(code, 'co_'+name)))
    return new.code(*args)

def rename_function(fn, name):
    code = copy_code_with_changes(fn.func_code, name=name)
    return new.function(code, fn.func_globals, name)

def test():
    raise RuntimeError

x = rename_function(test, '<anonymous>')

Which produces the output:
Traceback (most recent call last):
  File "D:\temp\", line 21, in ?
  File "D:\temp\", line 17, in <anonymous>
    raise RuntimeError

Duncan Booth                                             duncan at
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?

More information about the Python-list mailing list