def <dynamic function name> () syntax ?

Remco Gerlich scarblac at pino.selwerd.nl
Wed Apr 4 13:58:18 EDT 2001


Bruce Edge <bedge at troikanetworks.com> wrote in comp.lang.python:
> Can the follwoing be accomplished in Python?
> 
> I want to create a func named "abc":
> 
> >>> name="abc"
> 
> >>> eval ("name")
> 'abc'
> 
> >>> def eval ("name") ():
>   File "<stdin>", line 1
>     def eval ("name") ():
>                    ^
> SyntaxError: invalid syntax

Well, 

deff tempfunc():
   print whee
exec(name+" = tempfunc")
del tempfunc

Works. But how would you use the function? Maybe it's easier to use
some dictionary, ie

def tempfunc():
   print whee
function_dict = {name: tempfunc}
del tempfunc

# Run it
function_dict[name]()

If you want the function to be in some module, you can use setattr()
to make it.

import somemodule
def tempfunc():
   print whee
setattr(somemodule, name, tempfunc)
del tempfunc

# Run it
getattr(somemodule, name)()

But somehow I feel you don't need it anyway. Are you sure you're not trying
to port some idea from another language too literally? In Python you usually
don't care about the name of the function when passing it to other things,
as you can just pass the function itself...

-- 
Remco Gerlich



More information about the Python-list mailing list