-3

How to call multiple functions based on the input values. We can implement this with dictionary without using if-else by below:

def fun1(a, b, c) :
 ....
def fun2() :
 ....
def fun3() :
.....


dict{1 : fun1,
     2 : fun2,
     3 : fun3}

dict[1](input arguments)

But if the input parameters of different functions are different how can we pass input parameters without if-else. The idea of this approach is to avoid conditions and directly call functions based on input values.

5
  • Why not make one function that returns different outputs based on the input parameters (passed as **kwargs for example)? Commented Jun 23, 2022 at 19:06
  • Please clarify if you are indeed using Python 2. Otherwise remove the tag. Commented Jun 23, 2022 at 19:22
  • Try looking at Calling functions with parameters using a dictionary in Python. Commented Jun 23, 2022 at 19:26
  • In general you wouldn't put functions with different arguments in the same dictionary, precisely because of this problem. Commented Jun 23, 2022 at 19:36
  • What is your use case? I'm not sure if a dictionary is the best way to store these functions. Commented Jun 24, 2022 at 0:58

1 Answer 1

0

You can try *args method

def fun1(a, b, c):
    print("1", a, b, c)

def fun2(a):
    print("2", a)

def fun3():
    print("3")

fun_map = {
    1 : fun1,
    2 : fun2,
    3 : fun3
}

sample calls

inputs = (1,2,3)
fun_map[1](*inputs)
# output: 1 1 2 3

inputs = (1, )
fun_map[2](*inputs)
# output: 2 1

inputs = ()
fun_map[3](*inputs)
# output: 3

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.