dynamic function names

Alex Martelli aleax at aleax.it
Mon Apr 28 04:41:50 EDT 2003


<posted & mailed>

Bram Stolk wrote:

> Hello,
> 
> Is it possible in Python to define functions with a dynamic name?

Yes, but not with the def statement.


> something like:
> 
> def make_func(funcname) :
>   def funcname :

Syntax error -- you're missing parentheses here before the colon.

>     print "This func is named", funcname
> 
> make_func(foo)
> make_func(bar)
> 
> The code above fails due to foo being unknown,
> however, when calling as make_func("foo"), the "foo" string
> cannot be used as a funcname.

Actually, if you fix the syntax error it will work, but not do
what you want:

>>> def makefunc(funcname):
...   def funcname(): print "this function is named", funcname
...   return funcname
...
>>> f = makefunc('foo')
>>> f()
this function is named <function funcname at 0x402c09cc>
>>>

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


Alex





More information about the Python-list mailing list