Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function from a stored string in Python [duplicate]

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

like image 630
Fonky44 Avatar asked Feb 14 '17 13:02

Fonky44


3 Answers

Use a dict mapping names to functions.

call_dict = {
    'foo': foo,
    'bar': bar
}
call_dict[callfunction]()
like image 61
Daniel Roseman Avatar answered Oct 21 '22 19:10

Daniel Roseman


You can do this :

eval(input("What function do you want to call? ") + '()')
like image 30
Jarvis Avatar answered Oct 21 '22 18:10

Jarvis


It is quite common in Python to use the command pattern. First move all of your functions into a class, and give them names which have a prefix that isn't used in the input. Then use getattr() to find the correct function and call it.

class Commands():
   def cmd_foo(self):
       print("Foo")

   def callFunction(self, name):
       fn = getattr(self, 'cmd_'+name, None)
       if fn is not None:
            fn()

This has a couple of advantages over Daniel's call_dict: you don't have to list the name of the functions a second time, and you don't have to list the callable functions a second time either.

The 'cmd_' prefix is there to ensure you can have other methods in the class but still control exactly which ones are directly callable.

like image 34
Duncan Avatar answered Oct 21 '22 17:10

Duncan