string to function reference
Alex Martelli
aleaxit at yahoo.com
Fri Sep 1 09:08:09 EDT 2000
"Igor V. Rafienko" <igorr at ifi.uio.no> wrote in message
news:xjvem34ibkk.fsf at ganglot.ifi.uio.no...
> 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?
thefun=__dict__[s]
thefun()
You can wrap that in a function, of course (warning, untested):
def callit(funname,*args,dict=None):
if not dict: dict=globals()
funobj=dict[funname]
return apply(funobj,args)
so you can say, in your case,
callit(s)
Alex
More information about the Python-list
mailing list