0

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.

1
  • You could put your functions in a dictionary, or access them via the globals() dictionary. Commented Jul 30, 2020 at 12:25

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.