Victor Victor - 6 months ago 16
Python Question

Python methods and "switches"

I'm trying to use a dictionary as a switch statement as in

def add(first, second):
return first + second

def sub():
return something

operations = {
"Add": add,
"Sub": sub

ret_val = operations[operation]

Now how can I pass the arguments to add and sub and get their response? Currently, I don't pass anything to the methods, and testing the ret_val. What I see is the operation getting called, but the return doesn't come back. What I get is the pointer to the operation method.



To call a function, put the arguments in parentheses after it, just like when you call a function directly by its name.

ret_val = operations[operation](1, 2)

Note that for this to work properly, all the functions in operations need to take the same number of arguments. So it won't work if add() takes two arguments but sub() takes none, as you've shown.