string to function reference

Igor V. Rafienko igorr at
Fri Sep 1 13:41:31 CEST 2000


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.

"This 'love' intrigues me -- teach me to fake it"
	-- Dr. Zoidberg from "Why must I be a Crustacean in love?"

More information about the Python-list mailing list