PersianGulf PersianGulf - 1 year ago 63
Python Question

order of parameters of function call of python

Suppose I have a

10 args

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

Sometimes, I need to call it with only
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 Source

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:


or like this:

a = {'arg1':1, 'arg3':2}

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


{'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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download