Calling functions with parameters using a dictionary in Python

dictionary, function, parameters, python

Solution

I would do this using `functools.partial` to specify the arguments when the dictionary is created:

from functools import partial

options = {0: FunctionZero,   
           1: FunctionOne,    
           2: FunctionTwo,
           3: partial(FunctionThree, True)} 

Note that this also allows additional parameters to be passed when the function is called (as long as all the functions in the dictionary have the same parameters missing after `partial` has been called):

def test(one, two, three=None, four=None):
    ...

def test2(one, two, three=None):
    ...

options = {1: partial(test, 1, three=3, four=4),
           2: partial(test2, 1, three=3)}

...

options[choice](2) # pass the 'two' argument both functions still require

Problem

I'm making a program which has a main menu that asks the user to input an option and store it in integer `option1`, which is looked up in dictionary `options`. The corresponding function is then run. The following code works if the functions have no parameters: ``` options = {0 : FunctionZero, # Assign functions to the dictionary 1 : FunctionOne, 2 : FunctionTwo, 3 : FunctionThree} options[option1]() # Call the function ``` If the functions have parameters the above code doesn't work as the `()` part assumes the functions have no parameters, but I tried the following, which stores the functions' names and parameters in tuples within the dictionary: ``` options = {0 : (FunctionZero,""), # FunctionsZero, FunctionOne 1 : (FunctionOne,""), # and FunctionTwo have no parameters 2 : (FunctionTwo,""), 3 : (FunctionThree,True)} # FunctionThree has one parameter if options[option1][1] == "": # Call the function options[option1][0]() else: options[option1][0](options[option1][1]) ``` This code seems to work fine, but I was wondering if there's a better way to do this, especially if the functions require several parameters? In other languages like C# I'd probably use a switch or case statement (which is not in Python) and I'm avoiding using `if...elif` statements for this.

Original source