Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python function call with variable

Tags:

python

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?
like image 286
pkdkk Avatar asked Dec 13 '10 16:12

pkdkk


People also ask

Can you assign a function call to a variable in Python?

In Python, we can assign a function to a variable. And using that variable we can call the function as many as times we want. Thereby, increasing code reusability. Simply assign a function to the desired variable but without () i.e. just with the name of the function.

Can you call a variable from a function?

The variable can be assigned to the function object inside the function body. So the variable exists only after the function has been called. Once the function has been called, the variable will be associated with the function object. This variable can now be used anywhere inside or outside any function.


2 Answers

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()
like image 81
John Kugelman Avatar answered Oct 17 '22 02:10

John Kugelman


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.

like image 29
chrisaycock Avatar answered Oct 17 '22 00:10

chrisaycock