Search code examples
python-3.xfunctionif-statementuser-input

chosing a function without if statement in python


Imagine having 200 functions, which represent 200 ways to solve a problem or calculate something like

def A():
   ...
   
def B():
   ...
.
.
.

and the method will be chosen as an input argument, meaning the user decides which method to use, giving this as an argument while running the program like "A" for function/method A. how to chose that function without if-checking the name of every single function in python.


Solution

  • You can use a dictionary to access directly the function that you need in O(1) complexity. For example:

    def A(x):
       pass
    
    def B(x):
       pass
    
    func_map = {"A": A, "B": B}
    

    Say that you store the user input in a variable chosen_func, then to select and run the right function, do the following:

    func_map[chosen_func](x)
    

    Example:

    In [1]: def A(x): 
       ...:     return x + x 
     
    In [2]: def B(x): 
       ...:     return x * x  
    
    In [3]: func_map = {"A": A, "B": B}
    
    In [4]: func_map["A"](10)
    Out[4]: 20
    
    In [5]: func_map["B"](10)
    Out[5]: 100