def test():
print 'test'
def test2():
print 'test2'
test = {'test':'blabla','test2':'blabla2'}
for key, val in test.items():
key() # Here i want to call the function with the key name, how can i do so?
asked Dec 13, 2010 at 16:50
pkdkk
3,9818 gold badges49 silver badges72 bronze badges
-
1possible duplicate of Calling a function of a module from a string with the function's name in Pythoncfi– cfi2015年09月14日 09:44:25 +00:00Commented Sep 14, 2015 at 9:44
4 Answers 4
You could use the actual function objects themselves as keys, rather than the names of the functions. Functions are first class objects in Python, so it's cleaner and more elegant to use them directly rather than their names.
test = {test:'blabla', test2:'blabla2'}
for key, val in test.items():
key()
answered Dec 13, 2010 at 16:53
John Kugelman
365k70 gold badges555 silver badges600 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
John has a good solution. Here's another way, using eval():
def test():
print 'test'
def test2():
print 'test2'
mydict = {'test':'blabla','test2':'blabla2'}
for key, val in mydict.items():
eval(key+'()')
Note that I changed the name of the dictionary to prevent a clash with the name of the test() function.
answered Dec 13, 2010 at 17:00
chrisaycock
38.2k15 gold badges94 silver badges128 bronze badges
4 Comments
Daniel DiPaolo
Oof, not sure why you'd ever use this over the "function objects as keys themselves" method. If anything, you may be introspecting using something like
hasattr, but never ever evalchrisaycock
@Daniel I didn't say it was pretty! :D
martineau
This works, but
eval() has a lot of overhead to use it just calling a function. There's other better, way more "Pythonic" ways...Karl Knechtel
... like, for example, looking up the name in
globals() and/or locals() perhaps? :)def test():
print 'test'
def test2():
print 'test2'
assign_list=[test,test2]
for i in assign_list:
i()
def test():
print 'test'
def test2():
print 'test2'
func_dict = {
"test":test,
"test2":test2
}
test = {'test':'blabla','test2':'blabla2'}
for key, val in test.items():
func_dict[key]()
Comments
lang-py