In the following method definitions, what does the *
and **
do for param2
?
def foo(param1, *param2): def bar(param1, **param2):
What does ** (double star) and * (star) do for parameters? They allow for functions to be defined to accept and for users to pass any number of arguments, positional ( * ) and keyword ( ** ).
Enclosing a phrase between two asterisks is used to denote an action the user is "performing", e.g. *pulls out a paper* , although this usage is also common on forums, and less so on most chat rooms due to /me or similar commands.
Here single asterisk( * ) is also used in *args. It is used to pass a variable number of arguments to a function, it is mostly used to pass a non-key argument and variable-length argument list.
The asterisk (star) operator is used in Python with more than one meaning attached to it. Single asterisk as used in function declaration allows variable number of arguments passed from calling environment. Inside the function it behaves as a tuple.
The *args
and **kwargs
is a common idiom to allow arbitrary number of arguments to functions as described in the section more on defining functions in the Python documentation.
The *args
will give you all function parameters 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 keyword arguments except for those corresponding to a formal parameter as a dictionary.
def bar(**kwargs): for a in kwargs: print(a, kwargs[a]) bar(name='one', age=27) # name one # age 27
Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments:
def foo(kind, *args, **kwargs): pass
It 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 usage 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 an assignment (Extended Iterable Unpacking), though it gives 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 semantic (refer PEP 3102):
def func(arg1, arg2, arg3, *, kwarg1, kwarg2): pass
Such function accepts only 3 positional arguments, and everything after *
can only be passed as keyword arguments.
dict
, semantically used for keyword argument passing, are arbitrarily ordered. However, in Python 3.6, keyword arguments are guaranteed to remember insertion order.**kwargs
now corresponds to the order in which keyword arguments were passed to the function." - What’s New In Python 3.6 If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With