Sub topic 7
Fixing it with a None sentinel
This chapter assumes you can define and call functions, know that a default value is evaluated once when def runs, and have seen the mutable default bug from the previous chapters. Here you will fix that bug and learn where the fix goes wrong.
The idea
A sentinel is a placeholder value that means "the caller gave me nothing." The default in the signature is None, which is immutable and safe to share. The function body then builds the real default each time it runs.
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']The [] now sits inside the function body, so it is evaluated on every call that needs it. Each call that omits items gets a new list. Only None is stored in the function's __defaults__, and None cannot be mutated.
The callout below summarizes the rule.
What happens on each call
The two paths through the function differ in where the list comes from.
When the caller passes a list, the function mutates that list. This is often what you want, as in list.append. If you want to leave the caller's data alone, see the copying section below.
Test with `is None`, not truthiness
A common mistake is to write if not items: instead of if items is None:. An empty list is falsy, so the two tests give different results for a list the caller passed in.
def add_item(item, items=None):
if not items: # wrong test
items = []
items.append(item)
return items
shared = []
add_item("a", shared)
print(shared) # [] (the caller's empty list was thrown away)The caller passed shared on purpose. The function treated it as "nothing supplied" because it was empty, and appended to a different list. The same problem affects 0, "", {}, and False. Use is None whenever those values are legitimate arguments.
Other mutable defaults
Lists are the usual example, but the same pattern applies to dicts, sets, and instances of your own classes.
def register(name, registry=None):
if registry is None:
registry = {}
registry[name] = len(registry)
return registry
print(register("alpha")) # {'alpha': 0}
print(register("beta")) # {'beta': 0}
print(register("gamma", {"alpha": 0})) # {'alpha': 0, 'gamma': 1}You do not need a sentinel for immutable defaults. Numbers, strings, booleans, None, and tuples are safe to write directly in the signature. An empty tuple () is a good default when you want "an empty sequence" and do not need to change it.
Defaults that must be fresh on every call
A mutable object is not the only value that needs delaying. Anything that should be computed per call has the same problem, such as the current time.
from datetime import datetime, timezone
def stamp_frozen(message, when=datetime.now(timezone.utc)):
return f"{when.isoformat()} {message}" # same time on every call
def stamp(message, when=None):
if when is None:
when = datetime.now(timezone.utc)
return f"{when.isoformat()} {message}" # time of this callstamp_frozen evaluates datetime.now(...) once, when def runs. A long-running program will then log the time it started, forever. stamp reads the clock each time.
Defaults that depend on other parameters
A default expression cannot refer to another parameter of the same function. def f(a, b=a) fails at definition time because a is not a name there. A sentinel solves this too.
def windows(data, size, step=None):
if step is None:
step = size
return [data[i:i + size] for i in range(0, len(data), step)]
print(windows([1, 2, 3, 4, 5], 2)) # [[1, 2], [3, 4], [5]]
print(windows([1, 2, 3, 4, 5], 2, 1)) # [[1, 2], [2, 3], [3, 4], [4, 5], [5]]Here None means "use size." The signature documents that step is optional, and the body defines what the missing value means.
Do not mutate the caller's data by accident
With the basic pattern, a list passed by the caller is modified in place. If your function is meant to return a new result and leave its input alone, copy the input.
def with_item(item, items=None):
result = [] if items is None else list(items)
result.append(item)
return result
original = ["a"]
updated = with_item("b", original)
print(original) # ['a']
print(updated) # ['a', 'b']Decide which behavior the function promises and say so in the docstring. Mixing the two is a bug source. A function that sometimes mutates its argument and sometimes returns a copy is hard to reason about.
When None is a valid argument: a private sentinel
The None pattern fails when None is a meaningful value for the caller. For example, dict.get(key, None) and dict.get(key) mean the same thing, but a function that raises KeyError when no default is given needs to tell "no default" apart from "default is None". For that, create a unique object that no caller can pass by accident.
_MISSING = object()
def get_setting(settings, key, default=_MISSING):
if key in settings:
return settings[key]
if default is _MISSING:
raise KeyError(key)
return default
config = {"debug": None}
print(get_setting(config, "debug")) # None
print(get_setting(config, "port", None)) # None
print(get_setting(config, "port", 8080)) # 8080
try:
get_setting(config, "port")
except KeyError as error:
print("missing:", error) # missing: 'port'object() creates a new instance that is equal only to itself, so the is test cannot match anything the caller supplies. Name it with a leading underscore so it stays private to the module. The cost is readability: inspect.signature shows default=<object object at 0x...>. For a nicer display, make a small class with a __repr__ that returns something like <MISSING>.
Sentinel pattern checklist
| Situation | Signature default | Body check |
|---|---|---|
| Fresh list, dict, or set per call | `None` | `if x is None: x = []` |
| Value computed per call (time, random) | `None` | `if x is None: x = compute()` |
| Default depends on another parameter | `None` | `if x is None: x = other` |
| `None` is a valid caller value | `_MISSING = object()` | `if x is _MISSING: ...` |
| Immutable constant | The constant itself | None needed |
Documenting what None means
A reader of def windows(data, size, step=None) cannot tell what None stands for. Add a type hint and a docstring line that gives the meaning.
def windows(data: list, size: int, step: int | None = None) -> list:
"""Split data into chunks of `size`.
step: distance between chunk starts. None means the same as size,
so chunks do not overlap.
"""
if step is None:
step = size
return [data[i:i + size] for i in range(0, len(data), step)]The hint int | None warns callers that None is accepted, and the docstring explains the behavior. Without both, the sentinel becomes a hidden rule.
Common errors
- Writing
if not x:orx = x or [], which replaces valid empty arguments. - Forgetting the check entirely and using
items.append(...)onNone, which raisesAttributeError: 'NoneType' object has no attribute 'append'. - Using
==instead ofis. Some classes define__eq__so thatobj == Nonecan be true. Useis None. - Reusing one module-level list as the "default" inside the body, such as
items = DEFAULT_ITEMS. That shares one object across calls again, so copy it withlist(DEFAULT_ITEMS).
Exercise
This function should return a new dict with a "created" key added to the options the caller gives, and use an empty dict when none are given. It has two bugs. Name them and write a corrected version. def build(name, options={}): if not options: options = {} options["created"] = True options["name"] = name return options
Show answer
First, the default {} is a single shared dict created at definition time, so the signature itself is the mutable default bug. Second, if not options replaces an empty dict the caller passed, and the function mutates the caller's dict when one is passed. Corrected version:
def build(name, options=None):
result = {} if options is None else dict(options)
result["created"] = True
result["name"] = name
return result
The default is None, the test is is None, and dict(options) copies the input so the caller's dict is unchanged.
Exercise
You write def fetch(url, timeout=_MISSING) with _MISSING = object(). A caller needs to pass timeout=None to mean "wait forever," and omitting it should mean "use 30 seconds." Write the body check that supports both.
Show answer
Compare against the private sentinel, not None:
def fetch(url, timeout=MISSING):
if timeout is MISSING:
timeout = 30
return (url, timeout)
Omitting timeout gives 30. Passing timeout=None keeps None, which the function can interpret as "wait forever." A plain None default could not distinguish these two cases.