0

I have two user defined functions, like this:

def test_sum(a,b):
    x = a+b
    return x

def test_mean(a,b,c):
    z = a+b+c
    return z

using dictionary, based on the user interest one of the function is selected

func = {
    'sum_test': test_sum,
    'mean_test': test_mean
}

user_input = 'sum_test'

if user_input in func:
    print(func[user_input](10, 15))

How to pass the function arguments dynamically similar to how function is selected by user? (For the test_sum function I know there are two arguments so I gave 10, 15, but for the test_mean function there are three arguments so I have to change 10, 15 to 10, 15, 20 and I have to do this every time when a function changes.)

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Nirmal
  • 5
  • 1

1 Answers1

1

there are three ways to solve your problem. The first and cleaner one is to use iterables such as a list:

def test_sum(vals):
    return sum(vals)

def test_mean(vals):
    return test_sum(vals)/len(vals)

func = {
    'sum_test': test_sum,
    'mean_test': test_mean
}

user_input = 'sum_test'

if user_input in func:
    print(func[user_input]([10, 15]))

Note that the [10, 15] creates a list object containing the values 10 and 15.

If using iterables is not an option (for instance because your functions expect non-uniform inputs) you follow mkrieger1's suggestion.

A third alternative is using a dictionary. You can find an example here if you go to the section "Passing Dictionary as kwargs".

C Hecht
  • 932
  • 5
  • 14