Default arguments
A default argument is the value a parameter takes when the caller omits it. Python evaluates each default once, when the def statement runs, and reuses that same object on every later call.
Detailed Explanation
Defaults exist so that one function can serve both the common case and the unusual one. open(path) reads text; open(path, "rb") reads bytes. Callers who do not care about the extra knob never see it. Languages without defaults solve this with overloads or with a second function name; Python solves it in the signature.
The mechanics are ordinary. Parameters with defaults must come after parameters without them, and the defaults are stored on the function object itself, in __defaults__ for positional parameters and __kwdefaults__ for keyword-only ones.
The part that surprises people is when the default is computed. Python evaluates the expression once, at definition time, not on each call. def report(day=date.today()) freezes the day your program started. Every later call reports that same stale date, and the bug only shows up after the process has been running past midnight.
The same rule produces the most famous trap in the language: the mutable default. def add_item(item, cart=[]) creates one list, once. Each call that omits cart gets that same list, still holding everything previous callers added. The function appears to remember state it never asked for.
The fix is a sentinel. Use None as the default, then build the real value inside the body. Now every call that omits the argument gets a fresh object, and the default is documented in the signature as "nothing supplied".
None fails as a sentinel when None is itself a meaningful value. If timeout=None must mean "wait forever", you cannot also use it to mean "not specified". Create a unique module-level object, _MISSING = object(), and compare with is. Standard-library code does exactly this; inspect.Parameter.empty and dataclasses.MISSING are the same idea.
For dataclasses the answer is built in: field(default_factory=list) calls the factory per instance. A dataclass with a bare = [] default raises ValueError at class-creation time, because the language learned from the trap.
Two style points. First, prefer immutable defaults: numbers, strings, tuples, None, and frozensets are safe because nothing can mutate them. Second, boolean flags read badly positionally. render(page, True, False) tells a reader nothing, so put flags after a bare * to force keyword use.
Finally, a default is part of your public contract. Changing one changes behaviour for every existing caller without changing a single call site, which makes it a quiet source of regressions in libraries.
Code Examples
# The mutable-default trap: the list is created once, when 'def' runs.
def add_item(item, cart=[]):
cart.append(item)
return cart
print(add_item("apple")) # ['apple']
print(add_item("bread")) # ['apple', 'bread'] <- the SAME list as before
print(add_item.__defaults__) # (['apple', 'bread'],) the default itself grew
# The fix: a None sentinel, with the real default built per call.
def add_item_fixed(item, cart=None):
if cart is None: # None means "the caller supplied nothing"
cart = [] # a fresh list every time
cart.append(item)
return cart
print(add_item_fixed("apple")) # ['apple']
print(add_item_fixed("bread")) # ['bread']import time
# WRONG: time.time() runs once, while the def statement is being executed.
def elapsed_since(start=time.time()):
return time.time() - start
frozen = elapsed_since.__defaults__[0]
time.sleep(0.05)
print(elapsed_since.__defaults__[0] == frozen) # True <- never refreshed
# RIGHT: compute inside the body so each call sees a current value.
def elapsed_since_fixed(start=None):
if start is None:
start = time.time()
return time.time() - start
print(round(elapsed_since_fixed(), 3)) # 0.0from dataclasses import dataclass, field
_MISSING = object() # unique sentinel: None is a real value below
def set_timeout(seconds=_MISSING):
if seconds is _MISSING:
return "using the global default"
return f"timeout set to {seconds!r}"
print(set_timeout()) # using the global default
print(set_timeout(None)) # timeout set to None <- None means "no limit"
@dataclass
class Session:
user: str
# default_factory is the dataclass answer to the mutable-default trap
scopes: list[str] = field(default_factory=list)
print(Session("ana").scopes is Session("bo").scopes) # FalseCommon Gotchas
Mutable defaults are shared between calls
`def f(items=[])` or `def f(cache={})` creates one object at definition time, and every call that omits the argument mutates it. Default to `None` and build the container in the body.
Defaults capture the value at import time
`def report(day=date.today())` or `def connect(host=os.getenv("HOST"))` freeze whatever was true when the module loaded. Read the live value inside the function instead.
`None` is a poor sentinel when `None` is meaningful
if `None` legitimately means "no timeout" or "no limit", you cannot also use it for "not supplied". Use a private `object()` sentinel and compare with `is`.
Positional boolean flags read badly
`archive(path, True, False)` is unreadable at the call site. Put flags after a bare `*` so callers must write `archive(path, compress=True, overwrite=False)`.