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
Use a dict mapping names to functions.
call_dict = {
'foo': foo,
'bar': bar
}
call_dict[callfunction]()
You can do this :
eval(input("What function do you want to call? ") + '()')
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With