Statespressions? (Re: Draft Pep (was: Re: Let's Talk About Lambda Functions!))
Duncan Booth
duncan at NOSPAMrcp.co.uk
Thu Aug 8 06:07:15 EDT 2002
Michael Hudson <mwh at python.net> wrote in
news:lkadnxog0r.fsf at pc150.maths.bris.ac.uk:
> Duncan Booth <duncan at NOSPAMrcp.co.uk> 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',
'code','consts','names','varnames','filename',
'name','firstlineno','lnotab'):
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>')
x()
-------------------
Which produces the output:
D:\temp>code.py
Traceback (most recent call last):
File "D:\temp\code.py", line 21, in ?
x()
File "D:\temp\code.py", line 17, in <anonymous>
raise RuntimeError
RuntimeError
--
Duncan Booth duncan at rcp.co.uk
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