python - What does ** (double star/asterisk) and * (star/asterisk) do for parameters? -
in following method definitions, *
, **
param2
?
def foo(param1, *param2): def bar(param1, **param2):
the *args
, **kwargs
common idiom allow arbitrary number of arguments functions described in section more on defining functions in python documentation.
the *args
give function parameters as tuple:
in [1]: def foo(*args): ...: in args: ...: print ...: ...: in [2]: foo(1) 1 in [4]: foo(1,2,3) 1 2 3
the **kwargs
give keyword arguments except corresponding formal parameter dictionary.
in [5]: def bar(**kwargs): ...: in kwargs: ...: print a, kwargs[a] ...: ...: in [6]: bar(name='one', age=27) age 27 name 1
both idioms can mixed normal arguments allow set of fixed , variable arguments:
def foo(kind, *args, **kwargs): pass
another usage of *l
idiom unpack argument lists when calling function.
in [9]: def foo(bar, lee): ...: print bar, lee ...: ...: in [10]: l = [1,2] in [11]: foo(*l) 1 2
in python 3 possible use *l
on left side of assignment (extended iterable unpacking), though gives list instead of tuple in context:
first, *rest = [1,2,3,4] first, *l, last = [1,2,3,4]
also python 3 adds new semantic (refer pep 3102):
def func(arg1, arg2, arg3, *, kwarg1, kwarg2): pass
such function accepts 3 positional arguments, , after *
can passed keyword arguments.
Comments
Post a Comment