string to function reference

Igor V. Rafienko igorr at ifi.uio.no
Fri Sep 1 07:41:31 EDT 2000


Hi,


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.



ivr
-- 
"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