Skip to content Skip to sidebar Skip to footer

Python Call Function From String

s = 'func' Now suppose there is function called func. How can i call in Python 2.7 call func when the function name is given as a string?

Solution 1:

The safest way to do this:

In [492]: def fun():
   .....:     print("Yep, I was called")
   .....:

In [493]: locals()['fun']()
Yep, I was called

Depending on the context you might want to use globals() instead.

Alternatively you might want to setup something like this:

defspam():
    print("spam spam spam spam spam on eggs")

defvoom():
    print("four million volts")

defflesh_wound():
    print("'Tis but a scratch")

functions = {'spam': spam,
             'voom': voom,
             'something completely different': flesh_wound,
             }

try:
    functions[raw_input("What function should I call?")]()
except KeyError:
    print("I'm sorry, I don't know that function")

You can also pass arguments into your function a la:

def knights_who_say(saying):
    print("We are the knights who say {}".format(saying))

functions['knights_who_say'] = knights_who_say

function = raw_input("What is your function? ")
iffunction == 'knights_who_say':
    saying = raw_input("What is your saying? ")
    functions[function](saying)
else:
    functions[function]()

Solution 2:

deffunc():
    print("hello")
s = "func"eval(s)()

In [7]: s = "func"

In [8]: eval(s)()
hello

Not recommended! Just showing you how.

Solution 3:

you could use exec. Not recommended but doable.

s = "func()"exec s 

Solution 4:

You can execute a function by passing a string:

exec(s + '()')

Post a Comment for "Python Call Function From String"