pythonpython-3.x

Call a function from a stored string in Python


What I need is something that gets the variable and if the variable is the name of a function, the function will be called. I am not trying to get a function from a module but from within the program itself

Example:

def foo():
    print("Foo")
callfunction = input("What function do you want to call? ")

callfunction() ## Not sure what to put here but but lets say callfunction is foo.

I don't want something like this because I have many functions:

if callfunction == "Foo"
    Foo()
else:
    print("No function with that name")

My question is something like this, but I ask for the Python syntax. I am using Python 3.5.1


Solution

  • You can do this :

    eval(input("What function do you want to call? ") + '()')