Collecting
def total(*args):
return sum(args)
total(1, 2, 3) gives args = (1, 2, 3). total() gives args = (). The function accepts any number of positional arguments without knowing in advance how many. Inside the function, args is an ordinary tuple.
Two stars do the same for keyword arguments:
def show(**kwargs):
show(name="ana", score=91) gives kwargs = {"name": "ana", "score": 91} — an ordinary dict.
The names args and kwargs are pure convention. *items and **options work the same way. The stars carry the meaning. Convention is strong enough here that using different names in a general-purpose helper will raise eyebrows, but in a specific function a descriptive name often reads better.
The reason these exist is that some functions genuinely do not know how many arguments they will receive. A logging function might accept any number of values to print. A decorator needs to forward whatever the wrapped function expects. A function that merges configuration dictionaries might take two or might take ten. Without *args and **kwargs, every one of those cases would require the caller to pack arguments into a list or dictionary by hand and the function to unpack them.
The same star syntax works at the call site, running in reverse. If you have a list of values and a function that takes separate arguments, f(*my_list) spreads the list into positional arguments. If you have a dictionary, f(**my_dict) spreads its keys into keyword arguments. This symmetry between definition and call is what makes the feature useful in practice rather than just a curiosity.
This page covers collecting with *args and **kwargs, the required argument order in a definition, spreading at the call site, and the common pattern of forwarding arguments through a wrapper function.
Order in a definition
def report(label, *values, **options):
Named params first, then *args, then **kwargs. Python needs the fixed ones before the variable ones so it knows what to bind where.
Spreading
The same star at a call site does the opposite job:
dims = [2, 3, 4]
volume(*dims) # same as volume(2, 3, 4)
Without the star you pass one arg. The list itself. And get a TypeError about missing params. With it, the list is spread across the params in order.
** does the same for a dict, matching keys to param names:
volume(**{"length": 2, "width": 3, "height": 4})
The pass-through pattern
This is where the two halves meet. It's by far the most common real use:
def logged(func, *args, **kwargs):
print("calling", func.__name__)
return func(*args, **kwargs)
logged accepts any of it and forwards it untouched. It doesn't need to know the signature of what it's wrapping. each decorator, each wrapper, each "do this then call that" helper is built on this shape.
Merging collections
The stars also work when building literals:
[*first, *second] {defaults, overrides}
The dict form is a neat way to layer configuration: later keys win, so overrides beat defaults.
Where you will actually meet them
Almost each use of *args and **kwargs in real code falls into one of three shapes, and recognising them makes the feature far less abstract.
The first is a function that truly takes an unknown number of things: print, max, os.path.join. These are rare to write and common to use.
The second is a wrapper. A decorator, a retry helper, a logging shim - any of it that stands in front of another function and passes the call along. Here the star forms aren't a convenience, they're the only way to write the wrapper without hard-coding the signature of all it might wrap.
The third is a subclass extending its parent. def __init__(self, *args, extra=None, **kwargs) accepts what the parent accepts, adds one option of its own, and forwards the rest with super().__init__(*args, **kwargs). This keeps working when the parent gains a param. This Is the whole point.
The cost of being too flexible
A signature of (*args, **kwargs) accepts all, and that is its problem and its purpose. No one can tell what the function wants by reading it. An editor can't autocomplete the call. A typo in a keyword name no longer raises a clear TypeError about an unexpected arg - it lands silently in kwargs and surfaces later as a missing key, or worse, as a default quietly being used instead of the value you thought you passed.
So the rule is about spot in the system rather than taste. At the surface, where people call your code right, name the params. In the middle, where you're forwarding a call you didn't make, use the stars. The further a function is from a human caller, the more flexibility costs you nothing.
Reading someone else's signature
When you meet def f(a, b=1, *args, c, **kwargs), read it in the order Python binds it. a is needed and spot-based. b is spot-based with a default. args collects any further spot-based args. c comes after *args, which makes it keyword-only and, because it has no default, needed by name. kwargs collects the rest.
The one that surprises people is c. any of it after *args can only be passed by keyword, whether or not it has a default. That is the mechanism behind keyword-only params, and it's why library authors at times write a bare * in a signature: it turns all after it into a name you've to say out loud at the call site.
Keyword-only and positional-only, and why they exist
The stars do a second job besides collecting: they mark boundaries in a signature. Two markers control how callers are allowed to pass args.
A bare * makes all after it keyword-only:
def connect(host, *, timeout=30, retries=3):
return host, timeout, retries
print(connect("db", timeout=5))
try:
connect("db", 5)
except TypeError as e:
print("TypeError:", e)
('db', 5, 3)
TypeError: connect() takes 1 positional argument but 2 were given
The reason to want this is readability at the call site. connect("db", 5, 2) tells a reader nothing about what 5 and 2 mean, and it silently changes meaning if the param order is ever edited. Forcing the names makes the call self-documenting and makes reordering the params a safe change.
A / does the opposite, marking all before it spot-based-only:
def distance(x, y, /):
return abs(x - y)
Now distance(3, 5) works and distance(x=3, y=5) doesn't. This is rarer, and the reason is the mirror image: it keeps the param *names* out of the API, so they can be renamed later without breaking callers. Most builtins are spot-based-only for just that reason. This Is why len(obj=x) fails.
The rule of thumb: make a param keyword-only when its meaning isn't obvious from the call site. This Means flags, options and any of it numeric that isn't the main subject.
What the stars cost you
*args, **kwargs accepts all, and the price is paid by each reader and each tool afterwards.
The signature stops documenting any of it. def process(*args, **kwargs) tells the next person nothing about what to pass. The only way to find out is to read the body — and then the body of what it forwards to.
Editors and type checkers lose their grip. Autocompletion has nothing to suggest, and a type checker can't verify a call it can't see the shape of. For a codebase using type hints, a star signature is a hole in the coverage that passes to each caller.
Errors move. A misspelled keyword arg would most times raise TypeError: unexpected keyword arg 'timeuot' at the call, naming the mistake. Absorbed into **kwargs it turns a missing key later, or — worse — a default silently used instead of the value you passed, which makes wrong output and no error at all.
None of that is an arg against the feature. It's an arg about where to use it. Wrappers and subclass forwarding need it and pay none of the cost, because there's no real signature to state. A function people call right should name its params.
Unpacking in the other direction
The two stars appear in three places and mean the same thing in all of them, which is easier to hold on to than three separate rules.
In a meaning they collect: def f(*args) gathers loose spot-based args into a tuple.
At a call site they spread: f(*items) hands each item over as a separate arg.
In a literal they merge: [*a, *b] builds one list from two, and {**a, **b} builds one dict from two, with later keys winning.
The last is worth dwelling on because it has quietly become the standard way to combine collections:
defaults = {"colour": "red", "size": 1}
overrides = {"size": 3}
print({**defaults, **overrides})
print([*"ab", *"cd"])
{'colour': 'red', 'size': 3}
['a', 'b', 'c', 'd']
Both build a new object and leave the originals alone. This Is the difference from update and extend. And in set the star runs backwards again: first, *rest = items collects rather than spreads. The star is on the receiving side.
A decorator, concretely
The pass-through pattern exists mainly so that decorators can be written, and seeing one whole makes the pieces click:
import functools
def announce(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print("calling", func.__name__, "with", args, kwargs)
result = func(*args, **kwargs)
print("->", result)
return result
return wrapper
@announce
def add(a, b=0):
return a + b
print(add(2, b=3))
print(add.__name__)
calling add with (2,) {'b': 3}
-> 5
5
add
Four things are happening. announce takes a function and returns a swap. wrapper accepts any of it with *args, **kwargs, so it can stand in front of any function at all. The forwarding call func(*args, **kwargs) spreads them back out, so add receives just what the caller wrote. And @announce above def add is shorthand for add = announce(add).
functools.wraps is the part people leave out and then miss. Without it, add.__name__ prints wrapper, the docstring is gone, and each traceback through the decorated function names the wrapper instead of the function. It copies the spotting fields across, and it's one line.
Note how the args arrive: 2 in args and b=3 in kwargs, just as the caller passed them. The wrapper doesn't know or need to know that add has a param called b.
Asking a function what it accepts
When you do need to know the signature. Validating a plugin, building a command-line interface, writing a framework — inspect answers it rather than parsing the source:
inspect.signature(func) returns an object listing the params, their defaults, their kinds (spot-based, keyword-only, *args, **kwargs) and any annotations. sig.bind(*args, **kwargs) matches a proposed call against it and raises the same TypeError the real call would. This Is how you check args before doing costly work.
This is also how a decorator can be smarter than pure forwarding. A caching decorator that wants a stable key needs to know that f(1) and f(a=1) are the same call. sig.bind plus apply_defaults norms both to the same thing, which no amount of inspecting args and kwargs right will do.
The star in assignment
The same star appears in set, and it's worth connecting to the rest rather than learning apart.
first, *rest = items binds the first item and collects all else into a list. *most, last = items does the mirror image. a, *middle, b = items takes both ends and collects what is between them. In each case the starred name gets a list — always a list, even when the right-hand side was a tuple or a string.
This is the collecting sense of the star, the same as in a meaning: the star marks the name that absorbs but many items are left over. The spreading sense is what you get on the other side of the equals sign, in a call or a literal.
Only one star is allowed per set, for the obvious reason that two would make the split ambiguous. And the non-starred names are still needed: unpacking a, *rest = [] raises. There's nothing for a, while *rest, = [] succeeds and gives an empty list.
Questions people ask about *args and **kwargs
Do the names args and kwargs matter? No, the stars carry the meaning. The names are a strong rule -purpose wrappers and worth replacing with a thing descriptive elsewhere.
Can I have *args without **kwargs? Yes, and the reverse. They're free.
What order do they go in? Named params, then *args, then keyword-only params, then **kwargs.
Is **kwargs sorted? Yes, it's a normal dict and keeps the order the caller used.
Can I pass a list where *args is expected? Only with a star: f(*items). Without it you pass the list as a single arg.
Why does f(**d) fail with "keywords must be strings"? Because a dict with non-string keys can't be turned into keyword args.
How do I forward all including the function's own new option? Take it as keyword-only, and forward *args, **kwargs unchanged: the new option is bound by name and never reaches the wrapped call.
*args and **kwargs: recap in one screen
- One star collects spot-based args into a tuple. Two collect keyword args into a dict.
- The same stars at a call site spread a collection back into args, and in a literal they merge collections.
- A bare
* in a signature makes what follows keyword-only. A / makes what precedes it spot-based-only. - The pass-through
f(*args, **kwargs) is what makes decorators and wrappers possible without knowing any signature. - A star signature costs docs, tooling and clear errors — use it where there's no real signature to state, not to avoid writing one.