dynamic function names

Duncan Booth duncan at NOSPAMrcp.co.uk
Mon Apr 28 05:52:57 EDT 2003


Alex Martelli <aleax at aleax.it> wrote in 
news:iP5ra.14084$3M4.382689 at news1.tin.it:

> See?  "def funcname():" *RE-BINDS* identifier funcname to
> refer to the function object.
> 
> So, what you need is to call function 'function' in module
> 'new'.  You can first build a temporary function with a def
> to give you the right code, globals, defaults and closure,
> and then pass each of these to new.function together with
> the funcname you want to use:
> 
>>>> import new
>>>> def makefunc(funcname):
> ...   def temp(): print "this function is named", funcname
> ...   f = new.function(temp.func_code, globals(), funcname,
> ...           temp.func_defaults, temp.func_closure)
> ...   return f
> ...
>>>> f = makefunc('foo')
>>>> f()
> this function is named foo
>>>> f.func_name
> 'foo'
>>>>
> 

Note that this code only works on Python 2.3 (because the closure argument 
to new.function didn't exist earlier), and even there if the function 'foo' 
throws an exception the traceback will still call it 'temp'.


-- 
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