3
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?

quesaionasis
  • 137
  • 1
  • 2
  • 11

4 Answers4

10

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]()
Wayne Werner
  • 49,299
  • 29
  • 200
  • 290
4
def func():
    print("hello")
s = "func"
eval(s)()

In [7]: s = "func"

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

Not recommended! Just showing you how.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
1

you could use exec. Not recommended but doable.

s = "func()"

exec s 
jramirez
  • 8,537
  • 7
  • 33
  • 46
0

You can execute a function by passing a string:

exec(s + '()')
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70