user3696282
user3696282

Reputation: 35

python function dictionary with variable number of parameters

I am trying to create a dictionary which maps strings to functions. The problem is, the functions can have different parameter lengths. Is there a way to handle this.

For ex:

myFuncDict
{
'A' : a    ----> def a(param1, param2)
'B  : b    ----> def b(param1)
'C' : c    ----> def c(param1, param2, param3)
}

I want to call functions like:
def test(k):
 myFuncDict[k](params)

How can i achieve this? kwargs or args is one way to go, but not sure how to handle the above using those without sending extra parameters.

Upvotes: 1

Views: 1277

Answers (1)

Chris
Chris

Reputation: 22963

Python actually makes this quite simple. You can simply unpack your container of arguments into the function call using the unpacking operator *. Here is an example:

def a(x):
    print(x)

def b(x, y):
    print x, y

dic = {'a': a, 'b': b}


def call_func(func, params):
    dic[func](*params) # *params is the magic.

call_func('a', (1))
call_func('b', (1, 2))

Upvotes: 3

Related Questions