Single asterisk
In function definition
A single asterisk indicates that all following arguments must be Python keyword arguments. Additionally, if the asterisk is immediately followed by a parameter (e.g. *args
) then args
holds all following positional arguments.
-
Standalone asterisk: Forces all arguments after the
*
to be passed as Python keyword argumentsdef foo(pos, *, forcenamed): return (pos, forcenamed) print(foo(pos=10, forcenamed=20)) print(foo(10, forcenamed=20)) try: print(foo(10, 20)) except TypeError as e: print(e)
-
Asterisk with parameter: Forces all arguments after the
*
to be passed as Python keyword arguments and collects positional arguments.def foo(pos, *args, forcenamed): return (pos, args, forcenamed) print(foo(pos=10, forcenamed=30)) print(foo(10, 20, 30, 30, forcenamed=50)) try: print(foo(10, 20)) except TypeError as e: print(e)
In function invocation
A single asterisk in a Python function invocation expands a tuple of positional arguments.
def foo(a, b, c):
return a, b, c
args = (10, 20, 30)
print(foo(*args))
Double asterisk
A double asterisk (i.e. **
) precedes a dictionary of Python keyword arguments.
def foo(a, b, **c):
return a, b, c
print(foo(10, 20))
print(foo(10, 20, c=30, d=40))
try:
print(foo(10, 20, 30))
except TypeError as e:
print(e)
In function invocation
A double asterisk in a Python function invocation expands a dictionary of keyword arguments.
def foo(a, b, c):
return a, b, c
kwargs = {'b': 20, 'c': 30}
print(foo(10, **kwargs))