string to function reference

Alex Martelli aleaxit at
Fri Sep 1 15:08:09 CEST 2000

"Igor V. Rafienko" <igorr at> wrote in message
news:xjvem34ibkk.fsf at
> I've got a string holding a name of the function in the same module:
> def foo():
>     print "I'm foo"
> s = "foo"
> The question is, how do I call the function foo given its name as a
> string. The three approaches I could see are:
> 1) exec, as in:
> exec s + "()"
> 2) globals(), as in:
> (globals()[ s ])()
> 3) __dict__, which is no better than globals().
> All of these approaches are simply waay too ugly, imvho. Does anyone
> see a simpler/cleaner/more elegant way of achieving this.

The call operation needs to be applied to the function object.  The
reference to the function object is in a dictionary, under a key you
have (the name you hold).  What's so "waay to ugly" about fetching
the function object from that dictionary, then calling it?


You can wrap that in a function, of course (warning, untested):

def callit(funname,*args,dict=None):
    if not dict: dict=globals()
    return apply(funobj,args)

so you can say, in your case,



More information about the Python-list mailing list