PersianGulf PersianGulf - 20 days ago 5
Python Question

order of parameters of function call of python

Suppose I have a

function
with
10 args
:

def foo(arg1,arg2,arg3,arg4.....):


Sometimes, I need to call it with only
arg1
and another time
arg1, arg4
, or
arg4 , arg7
.

My program doesn't specify the type of the function call. Does python have a way to help me?

Answer

One way to do it is to make the parameters optional:

def foo(arg1=None,arg2=None,arg3=None...)

which can be called like this:

foo(arg1=1,arg3=2)

or like this:

a = {'arg1':1, 'arg3':2}
foo(**a)

If this list of parameters is spinning out of control you could simply use **kwargs to let your function take an optional number of (named) keyword arguments:

def foo(**kwargs):
    print kwargs

params = {'arg1':1, 'arg2':2}

foo(**params)         # Version 1
foo(arg1=3,arg2=4)    # Version 2

Output:

{'arg1': 1, 'arg2': 2}
{'arg1': 3, 'arg2': 4}

Note: You can use one asterisk (*) for an arbitrary number of arguments that will be wrapped up in a tuple.

Comments