- What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
- 27 Answers 27
- Note:
- What does ** (double star) and * (star) do for parameters?
- Defining Functions
- Expansion, Passing any number of arguments
- New in Python 3: Defining functions with keyword only arguments
- Python 2 compatible demos
What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
This question is a very popular duplicate target, but unfortunately it’s often used incorrectly. Keep in mind that this question asks about defining functions with varargs ( def func(*args) ). For a question asking what it means in function calls ( func(*[1,2]) ) see here. For a question asking how to unpack argument lists see here. For a question asking what the * means in literals ( [*[1, 2]] ) see here.
@Aran-Fey: I think a better target for «what does it mean in function calls» is What does the star operator mean, in a function call?. Your link doesn’t really address the use of ** , and it a much narrower question.
This question is — like many very old questions — sort of backwards; usually a question should be about how to solve a problem in new code, rather than how to understand existing code. For the latter, if you are closing something else as a duplicate, consider stackoverflow.com/questions/1993727/… (although this only covers * and not ** ).
stackoverflow.com/questions/3394835/use-of-args-and-kwargs was also closed as a duplicate of this, but you might find it better than this one.
27 Answers 27
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 = 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
For example the following works in python 3 but not python 2:
>>> x = [1, 2] >>> [*x] [1, 2] >>> [*x, 3, 4] [1, 2, 3, 4] >>> x = >>> x >>>
Such function accepts only 3 positional arguments, and everything after * can only be passed as keyword arguments.
Note:
- A Python dict , semantically used for keyword argument passing, are arbitrarily ordered. However, in Python 3.6, keyword arguments are guaranteed to remember insertion order.
- «The order of elements in **kwargs now corresponds to the order in which keyword arguments were passed to the function.» — What’s New In Python 3.6
- In fact, all dicts in CPython 3.6 will remember insertion order as an implementation detail, this becomes standard in Python 3.7.
It’s also worth noting that you can use * and ** when calling functions as well. This is a shortcut that allows you to pass multiple arguments to a function directly using either a list/tuple or a dictionary. For example, if you have the following function:
def foo(x,y,z): print("x=" + str(x)) print("y=" + str(y)) print("z ", line 1, in TypeError: foo() got an unexpected keyword argument 'badnews'
The single * means that there can be any number of extra positional arguments. foo() can be invoked like foo(1,2,3,4,5) . In the body of foo() param2 is a sequence containing 2-5.
The double ** means there can be any number of extra named parameters. bar() can be invoked like bar(1, a=2, b=3) . In the body of bar() param2 is a dictionary containing
def foo(param1, *param2): print(param1) print(param2) def bar(param1, **param2): print(param1) print(param2) foo(1,2,3,4,5) bar(1,a=2,b=3)
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 ( ** ).
Defining Functions
*args allows for any number of optional positional arguments (parameters), which will be assigned to a tuple named args .
**kwargs allows for any number of optional keyword arguments (parameters), which will be in a dict named kwargs .
You can (and should) choose any appropriate name, but if the intention is for the arguments to be of non-specific semantics, args and kwargs are standard names.
Expansion, Passing any number of arguments
You can also use *args and **kwargs to pass in parameters from lists (or any iterable) and dicts (or any mapping), respectively.
The function recieving the parameters does not have to know that they are being expanded.
For example, Python 2’s xrange does not explicitly expect *args , but since it takes 3 integers as arguments:
>>> x = xrange(3) # create our *args - an iterable of 3 integers >>> xrange(*x) # expand here xrange(0, 2, 2)
As another example, we can use dict expansion in str.format :
>>> foo = 'FOO' >>> bar = 'BAR' >>> 'this is foo, and bar, '.format(**locals()) 'this is foo, FOO and bar, BAR'
New in Python 3: Defining functions with keyword only arguments
You can have keyword only arguments after the *args — for example, here, kwarg2 must be given as a keyword argument — not positionally:
def foo(arg, kwarg=None, *args, kwarg2=None, **kwargs): return arg, kwarg, args, kwarg2, kwargs
>>> foo(1,2,3,4,5,kwarg2='kwarg2', bar='bar', baz='baz') (1, 2, (3, 4, 5), 'kwarg2', )
Also, * can be used by itself to indicate that keyword only arguments follow, without allowing for unlimited positional arguments.
def foo(arg, kwarg=None, *, kwarg2=None, **kwargs): return arg, kwarg, kwarg2, kwargs
Here, kwarg2 again must be an explicitly named, keyword argument:
>>> foo(1,2,kwarg2='kwarg2', foo='foo', bar='bar') (1, 2, 'kwarg2', )
And we can no longer accept unlimited positional arguments because we don’t have *args* :
>>> foo(1,2,3,4,5, kwarg2='kwarg2', foo='foo', bar='bar') Traceback (most recent call last): File "", line 1, in TypeError: foo() takes from 1 to 2 positional arguments but 5 positional arguments (and 1 keyword-only argument) were given
Again, more simply, here we require kwarg to be given by name, not positionally:
def bar(*, kwarg=None): return kwarg
In this example, we see that if we try to pass kwarg positionally, we get an error:
>>> bar('kwarg') Traceback (most recent call last): File "", line 1, in TypeError: bar() takes 0 positional arguments but 1 was given
We must explicitly pass the kwarg parameter as a keyword argument.
Python 2 compatible demos
*args (typically said «star-args») and **kwargs (stars can be implied by saying «kwargs», but be explicit with «double-star kwargs») are common idioms of Python for using the * and ** notation. These specific variable names aren’t required (e.g. you could use *foos and **bars ), but a departure from convention is likely to enrage your fellow Python coders.
We typically use these when we don’t know what our function is going to receive or how many arguments we may be passing, and sometimes even when naming every variable separately would get very messy and redundant (but this is a case where usually explicit is better than implicit).
The following function describes how they can be used, and demonstrates behavior. Note the named b argument will be consumed by the second positional argument before :
def foo(a, b=10, *args, **kwargs): ''' this function takes required argument a, not required keyword argument b and any number of unknown positional arguments and keyword arguments after ''' print('a is a required argument, and its value is '.format(a)) print('b not required, its default value is 10, actual value: '.format(b)) # we can inspect the unknown arguments we were passed: # - args: print('args is of type and length '.format(type(args), len(args))) for arg in args: print('unknown arg: '.format(arg)) # - kwargs: print('kwargs is of type and length '.format(type(kwargs), len(kwargs))) for kw, arg in kwargs.items(): print('unknown kwarg - kw: , arg: '.format(kw, arg)) # But we don't have to know anything about them # to pass them to other functions. print('Args or kwargs can be passed without knowing what they are.') # max can take two or more positional args: max(a, b, c. ) print('e.g. max(a, b, *args) \n'.format( max(a, b, *args))) kweg = 'dict()'.format( # named args same as unknown kwargs ', '.join('='.format(k=k, v=v) for k, v in sorted(kwargs.items()))) print('e.g. dict(**kwargs) (same as ) returns: \n'.format( dict(**kwargs), kweg=kweg))
We can check the online help for the function’s signature, with help(foo) , which tells us
Let’s call this function with foo(1, 2, 3, 4, e=5, f=6, g=7)
a is a required argument, and its value is 1 b not required, its default value is 10, actual value: 2 args is of type and length 2 unknown arg: 3 unknown arg: 4 kwargs is of type and length 3 unknown kwarg - kw: e, arg: 5 unknown kwarg - kw: g, arg: 7 unknown kwarg - kw: f, arg: 6 Args or kwargs can be passed without knowing what they are. e.g. max(a, b, *args) 4 e.g. dict(**kwargs) (same as dict(e=5, f=6, g=7)) returns:
We can also call it using another function, into which we just provide a :
def bar(a): b, c, d, e, f = 2, 3, 4, 5, 6 # dumping every local variable into foo as a keyword argument # by expanding the locals dict: foo(**locals())
a is a required argument, and its value is 100 b not required, its default value is 10, actual value: 2 args is of type and length 0 kwargs is of type and length 4 unknown kwarg - kw: c, arg: 3 unknown kwarg - kw: e, arg: 5 unknown kwarg - kw: d, arg: 4 unknown kwarg - kw: f, arg: 6 Args or kwargs can be passed without knowing what they are. e.g. max(a, b, *args) 100 e.g. dict(**kwargs) (same as dict(c=3, d=4, e=5, f=6)) returns:
Example 3: practical usage in decorators
OK, so maybe we’re not seeing the utility yet. So imagine you have several functions with redundant code before and/or after the differentiating code. The following named functions are just pseudo-code for illustrative purposes.
def foo(a, b, c, d=0, e=100): # imagine this is much more code than a simple function call preprocess() differentiating_process_foo(a,b,c,d,e) # imagine this is much more code than a simple function call postprocess() def bar(a, b, c=None, d=0, e=100, f=None): preprocess() differentiating_process_bar(a,b,c,d,e,f) postprocess() def baz(a, b, c, d, e, f): . and so on
We might be able to handle this differently, but we can certainly extract the redundancy with a decorator, and so our below example demonstrates how *args and **kwargs can be very useful:
def decorator(function): '''function to wrap other functions with a pre- and postprocess''' @functools.wraps(function) # applies module, name, and docstring to wrapper def wrapper(*args, **kwargs): # again, imagine this is complicated, but we only write it once! preprocess() function(*args, **kwargs) postprocess() return wrapper
And now every wrapped function can be written much more succinctly, as we’ve factored out the redundancy:
@decorator def foo(a, b, c, d=0, e=100): differentiating_process_foo(a,b,c,d,e) @decorator def bar(a, b, c=None, d=0, e=100, f=None): differentiating_process_bar(a,b,c,d,e,f) @decorator def baz(a, b, c=None, d=0, e=100, f=None, g=None): differentiating_process_baz(a,b,c,d,e,f, g) @decorator def quux(a, b, c=None, d=0, e=100, f=None, g=None, h=None): differentiating_process_quux(a,b,c,d,e,f,g,h)
And by factoring out our code, which *args and **kwargs allows us to do, we reduce lines of code, improve readability and maintainability, and have sole canonical locations for the logic in our program. If we need to change any part of this structure, we have one place in which to make each change.