Sub topic 7
Fixing it with a None sentinel
This chapter assumes you know that a default value is evaluated once, when def runs, and that a mutable default such as [] is therefore shared between calls. Here you will learn the standard fix.
The pattern
A sentinel is a placeholder value that means "the caller gave nothing". For mutable defaults, None is the usual sentinel. The signature says items=None, and the body creates the real list on each call.
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item("a")) # ['a']
print(add_item("b")) # ['b']None is immutable and is created once, so sharing it between calls is harmless. The [] inside the body runs on every call that needs it, so each call gets a new list.
Test with `is None`, not truthiness
A common slip is to write if not items:. An empty list is falsy, so a caller who passes their own empty list gets it silently replaced.
def add_item(item, items=None):
if not items: # wrong: also true for []
items = []
items.append(item)
return items
mine = []
add_item("a", mine)
print(mine) # [] - the caller's list was ignoredUse is None so only the missing-argument case triggers the fallback.
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
mine = []
add_item("a", mine)
print(mine) # ['a']Other mutable defaults
The same pattern applies to dicts, sets, and any object that should be new for each call, such as a timestamp.
from datetime import datetime
def log(message, tags=None, when=None):
if tags is None:
tags = {}
if when is None:
when = datetime.now()
return {"message": message, "tags": tags, "when": when}Writing when=datetime.now() in the signature would capture the time at definition and reuse it forever. This is the same defect as the list bug, applied to a different type.
When None is a valid argument
Sometimes None is a meaningful value. For example, timeout=None may mean "wait forever", which differs from "use the default timeout". Then None cannot also mean "not provided". Create a private sentinel object that no caller can pass by accident.
_MISSING = object()
def fetch(url, timeout=_MISSING):
if timeout is _MISSING:
timeout = 30 # default when not provided
return (url, timeout)
print(fetch("a.com")) # ('a.com', 30)
print(fetch("a.com", timeout=None)) # ('a.com', None)Each call to object() returns a distinct instance, so is _MISSING matches only the module's own placeholder. The cost is that inspect.signature shows an unhelpful <object object at ...> default, so use this form only when you need it.
Return a new object, or modify the argument?
The sentinel fixes where a default list comes from. It does not decide whether a function should change a list the caller passed in. If a function appends to items, the caller's list changes. Document that behavior, or copy the list first with items = list(items) when you want to leave the caller's data alone.
| Situation | Approach |
|---|---|
| Default should be a fresh list, dict, or set | `param=None`, then `if param is None:` |
| `None` is a legitimate value | Private `object()` sentinel |
| Default is an immutable value (number, string, tuple) | Put it directly in the signature |
Exercise
This function should return a dict with a "retries" key. Callers sometimes pass an empty dict on purpose. Which line is wrong, and what is the fix? def configure(options=None): if not options: options = {} options.setdefault("retries", 3) return options
Show answer
if not options: is wrong. An empty dict passed by the caller is falsy, so it is replaced with a new dict and the caller's dict never receives the "retries" key. Use if options is None: so only an omitted argument (or an explicit None) triggers the new dict.