In the following method definitions, what does the * and ** for param2 ?
def foo(param1, *param2): def bar(param1, **param2):The *args and **kwargs is a common idiom for allowing an arbitrary number of arguments to functions as described in the more detailed section on function definitions in the Python documentation.
*args will give you all the parameters of the function as a tuple :
def foo(*args): for a in args: print(a) foo(1) # 1 foo(1,2,3) # 1 # 2 # 3 The **kwargs will give you all the keyword arguments except those for a formal parameter like a dictionary.
def bar(**kwargs): for a in kwargs: print(a, kwargs[a]) bar(name='one', age=27) # name one # age 27Both idioms can be mixed with normal arguments to allow a set of fixed arguments and some variables:
def foo(kind, *args, **kwargs): passIt is also possible to use this the other way around:
def foo(a, b, c): print(a, b, c) obj = {'b':10, 'c':'lee'} foo(100,**obj) # 100 10 lee Another use of the *l idiom is to unpack argument lists when calling a function.
def foo(bar, lee): print(bar, lee) l = [1,2] foo(*l) # 1 2 In Python 3, it is possible to use *l on the left side of a task ( Extended Iterable Unpacking ), although it returns a list instead of a tuple in this context:
first, *rest = [1,2,3,4] first, *l, last = [1,2,3,4]Also Python 3 adds new semantics (see PEP 3102 ):
def func(arg1, arg2, arg3, *, kwarg1, kwarg2): pass Such a function accepts only 3 positional arguments, and everything that * can only be passed as keyword arguments.
A Python dict , used semantically to pass keyword arguments, is ordered arbitrarily. However, in Python 3.6, keyword arguments are guaranteed to remember insertion order.
"The order of the elements in **kwargs now corresponds to the order in which the keyword arguments were passed to the function." - What's new in Python 3.6
In fact, all dicts in CPython 3.6 will remember the insertion order as an implementation detail, this becomes standard in Python 3.7.