Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Call Function from String [duplicate]

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?

like image 801
quesaionasis Avatar asked Jun 15 '26 19:06

quesaionasis


2 Answers

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:

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

def voom():
    print("four million volts")

def flesh_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? ")
if function == 'knights_who_say':
    saying = raw_input("What is your saying? ")
    functions[function](saying)
else:
    functions[function]()
like image 193
Wayne Werner Avatar answered Jun 17 '26 08:06

Wayne Werner


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

In [7]: s = "func"

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

Not recommended! Just showing you how.

like image 33
Padraic Cunningham Avatar answered Jun 17 '26 10:06

Padraic Cunningham