Lesson 12 of 52Functions
Arguments, *args and **kwargs
Use positional, keyword and default arguments, avoid the mutable default trap, and accept any number of arguments.
Open any real Python library and the function signatures look like def request(method, url, *, timeout=None, **kwargs). Every part of that is doing a job: forcing clarity, giving sensible defaults, passing options through. This lesson teaches you to read and write signatures like that, and covers the mutable default argument bug, which is probably the single most famous Python interview gotcha.
Positional and keyword arguments
When you call a function, you can pass arguments in two ways:
- Positional: matched to parameters by position.
book("Ada", 2). - Keyword: matched by name.
book(name="Ada", seats=2). Order no longer matters.
Press Run (⌘ Enter) to see what happens.You can mix them, but positional arguments must come first. book(name="Ada", 2, True) is a SyntaxError. Keyword arguments make calls self-documenting: book("Leo", 1, True) leaves the reader guessing what True means; window=True does not.
Default values
A parameter can have a default, used when the caller leaves it out. Parameters with defaults must come after those without.
Press Run (⌘ Enter) to see what happens.Notice the last call: keywords let you skip greeting and set only punctuation.
The mutable default trap
Here is the bug. Read it, predict it, then run it.
Press Run (⌘ Enter) to see what happens.The default value is created once, when the def statement runs, and stored on the function. It is not re-created on each call. So every call that relies on the default shares the very same list.
Running def creates the function and evaluates [] right now, once. The function keeps that list as its default.
The fix is to use None as the default (it is immutable, so sharing it is harmless) and create a fresh list inside the function:
Press Run (⌘ Enter) to see what happens.The rule: never use a mutable value (list, dict, set) as a default. Immutable defaults like 0, "", None or a tuple are fine.
def add(x, items=[]): items.append(x) return items add(1) print(add(2))
*args: any number of positional arguments
Sometimes you do not know how many arguments will come. A parameter written *args collects all extra positional arguments into a tuple. The name args is only a convention; the * is what matters.
Press Run (⌘ Enter) to see what happens.**kwargs: any number of keyword arguments
**kwargs collects all extra keyword arguments into a dict, mapping each name to its value.
Press Run (⌘ Enter) to see what happens.You will see **kwargs a lot in wrappers that pass options through to another function untouched.
What does this print?
def f(a, b=2, *args, c, **kwargs): print(a, b, args, c, kwargs) f(1, 3, 4, 5, c=6, d=7)
Keyword-only and positional-only parameters
You can force callers to use names, or forbid them, with two markers:
- Parameters after a bare
*are keyword-only. - Parameters before a
/are positional-only (Python 3.8+).
Press Run (⌘ Enter) to see what happens.Why bother? Keyword-only parameters stop mistakes like connect("db", 5432, 2.0, 1) where nobody can tell which number is which. Positional-only parameters let a library rename a parameter later without breaking callers, which is why many built-ins use them (len(obj, /)).
Put the parts of a full Python signature in the order they must appear.
- Tap the steps below in the right order.
Unpacking at the call site
The stars also work in the other direction. When calling a function, * spreads a list or tuple into positional arguments, and ** spreads a dict into keyword arguments.
Press Run (⌘ Enter) to see what happens.Match each piece of syntax to what it does.
How Python binds a call
When you call a function, Python matches arguments to parameters in a fixed sequence. Knowing it lets you read any TypeError about arguments and know exactly which rule fired.
Positional arguments take parameter slots in order. 1 goes to a, 2 goes to b.
Each rule has its own error message, so the message tells you which step failed. The fourth step has a useful twist: a positional-only parameter's name is free to appear in **kwargs.
Press Run (⌘ Enter) to see what happens.That is why functions that accept arbitrary keyword names, like a template renderer, make their own parameters positional-only. Without the /, a caller who passes a key that happens to match a parameter name gets a confusing error:
Press Run (⌘ Enter) to see what happens.Forwarding *args, **kwargs in wrappers
The most common real use of both stars together is forwarding: a wrapper receives whatever the caller passed and hands it, untouched, to another function. Logging, timing, retry and caching wrappers all look like this, and so do subclasses that pass options up with super().__init__(**kwargs).
Press Run (⌘ Enter) to see what happens.Three things to notice.
First, the bare wrapper loses the signature. Its name is wrapper and its parameters are (*args, **kwargs), so help(), your editor's autocomplete and any tool that inspects parameters (FastAPI does this to build its request parsing) see nothing useful. functools.wraps copies the name and docstring and sets __wrapped__, which inspect.signature follows back to the real function. You will build this properly in Decorators.
Second, forwarding is lazy about errors. The typo timout=1 passes straight through the wrapper and only fails when fetch itself is called. With one layer that is fine. With five layers of wrappers, the traceback points at the bottom and you have to work out where the bad argument came from.
Third, type checkers cannot see through *args, **kwargs on their own. A wrapper typed as Callable[..., Any] makes every call to the wrapped function unchecked. The fix is ParamSpec, covered in Typing Patterns for Real Code.
A few rules keep forwarding code honest:
- Do not copy defaults into the wrapper. If
fetchchanges its default timeout, a wrapper that also saystimeout=5.0silently overrides it. - If the wrapper needs one option, take it by name and forward the rest:
def wrapper(*args, verbose=False, **kwargs). The wrapper's own option never reaches the inner function. - Do not mutate
kwargsyou did not create in a way the caller can see.kwargsis a fresh dict per call, sokwargs.pop("x")is safe, but a dict you received as a plain argument is not yours to change.
Typing **kwargs with Unpack[TypedDict]
Annotating **kwargs has a catch. **kwargs: int does not mean "kwargs is an int". It means each value is an int, so the dict is dict[str, int]. Most real options are mixed types, which used to force **kwargs: Any and threw away all checking.
Since Python 3.12 (and earlier through typing_extensions), you can describe the exact keys with a TypedDict and Unpack:
from typing import NotRequired, TypedDict, Unpack
class RequestOptions(TypedDict):
timeout: NotRequired[float]
retries: NotRequired[int]
headers: NotRequired[dict[str, str]]
def get(url: str, **options: Unpack[RequestOptions]) -> str:
return send("GET", url, **options)
def post(url: str, body: bytes, **options: Unpack[RequestOptions]) -> str:
return send("POST", url, body=body, **options)
get("/users", timeout=2.0) # OK
get("/users", timout=2.0) # checker error: unexpected keyword "timout"
get("/users", retries="3") # checker error: str is not intThis is how you share one set of options across many functions without repeating a long keyword-only signature on each. At runtime nothing changes: annotations are not enforced, so the checks only happen in your editor and in CI with a checker such as mypy or pyright. TypedDict itself, including Required, NotRequired and ReadOnly, is covered in Typing Patterns for Real Code.
API design: the boolean-flag smell
Here is a call from a real code review: export(rows, True, False, ";"). Nobody can read that. Three habits fix most signature problems like it.
Make flags keyword-only. Put a bare * before any boolean or tuning option. The call becomes export(rows, header=True, quote=False, separator=";"), which documents itself, and you can add or reorder options later without breaking anyone.
Prefer explicit keyword-only parameters over **options. A function that reads its settings from **kwargs with .get() accepts typos silently, because every key is "allowed":
Press Run (⌘ Enter) to see what happens.The loose version used the default comma and nobody noticed. The strict version fails at the call site with a suggestion. Use **kwargs when you genuinely forward to something else, not as a lazy way to declare options.
A boolean that changes what the function does is often two functions. load(path, as_json=True) that returns a dict or a string depending on the flag is harder to type and test than load_json(path) and load_text(path). If there are more than two modes, take an enum instead of several booleans that can contradict each other (see Enums). A flag is fine when it tweaks behaviour, like reverse=True, rather than switching to a different job.
What does this print?
def connect(host, *, timeout=5, **extra):
return timeout, extra
print(connect("db", timout=1))Reading real standard library signatures
Signatures in the docs and in help() use exactly the syntax from this lesson. Once you can decode them, the docs answer most questions about how to call something.
Press Run (⌘ Enter) to see what happens.Read them one at a time:
sorted(iterable, /, *, key=None, reverse=False): the input is positional-only, and both options are keyword-only.sorted(xs, len)is an error; you must writekey=len.print(*args, sep=' ', end='\n', file=None, flush=False): any number of values, and every option after*argsis automatically keyword-only.len(obj, /)anddivmod(x, y, /): positional-only, so the C code never has to accept names.dict.get(self, key, default=None, /):d.get("k", 0)works, butd.get("k", default=0)raisesTypeError. This surprises people.str.split(self, /, sep=None, maxsplit=-1): here the options are normal parameters, so"a b c".split(None, 1)and"a b c".split(maxsplit=1)both work.
Some built-ins, like max, have no single signature at all, because they accept either one iterable or several values. Their docs show two forms: max(iterable, *, key=None) and max(arg1, arg2, *args, key=None).
sorted(iterable, /, *, key=None, reverse=False). Which call is valid?Average of anything
Write average(*nums) that accepts any number of positional arguments and returns their average as a float. With no arguments, return 0.0.
average(1, 2, 3) → 2.0
average(1, 2) → 1.5
average() → 0.0Fix the shared default
add_item(item, items) appends item to items and returns the list. If no list is passed, it should start a fresh empty list every time.
The obvious version, def add_item(item, items=[]), has a bug: every call without a list shares the same one.
add_item("a") # ['a']
add_item("b") # should be ['b'], the buggy version gives ['a', 'b']Write a version that works. If a list is passed, append to that exact list.
- keyword argument
- An argument passed by name,
f(x=1). Order does not matter, and it documents the call. - default value
- Used when the caller omits the argument. Evaluated once, when
defruns. - mutable default
- A list/dict/set default shared across calls. Use
Noneand create the object inside. - *args
- Collects extra positional arguments into a tuple.
- **kwargs
- Collects extra keyword arguments into a dict.
- keyword-only parameter
- A parameter after
*or*args; it can only be passed by name. - positional-only parameter
- A parameter before
/; it cannot be passed by name, so its name is free to appear in**kwargs. - forwarding
- A wrapper accepting
*args, **kwargsand passing them unchanged to another function. - Unpack[TypedDict]
- An annotation that gives each key in
**kwargsits own name and type for the type checker.