Missing or None? The Sentinel Pattern in Python

This article explains how a unique sentinel object lets a Python function distinguish an omitted argument from None, and why its identity must survive copying, pickling and comparison.

A green tree python coiled around a dark branch, its head raised and facing forward against a pale stone wall
Photo by kim hyo woon on Unsplash

Optional parameters in Python usually take None as their default, which works until None itself becomes a meaningful value that a caller may pass on purpose. The present article addresses the Sentinel pattern, which replaces that default with a unique object whose only purpose is to be recognized by its identity, so that a function can distinguish "no value was given" from "the value given was None". It explains why object() provides such a marker, compares it with a small class and with a single-member enumeration, and analyses the errors that appear when the marker is copied, pickled, compared with == or annotated. Telling absence apart from every possible value, None included, with a single comparison is the secret weapon of a sentinel.

When None Is a Valid Value

A default of None merges two different situations: the caller omitted the argument, or the caller passed None deliberately. The distinction matters whenever None carries meaning, for example in an update function where None clears a database field and an omitted argument leaves it unchanged. A module-level object() solves the problem, because every call to object() creates a new instance that no caller can produce by accident, and the is operator recognizes exactly that instance.

MISSING = object()

def update(record, email=MISSING):
    if email is not MISSING:
        record["email"] = email
    return record

print(update({"email": "[email protected]"}))               # Output: {'email': '[email protected]'}
print(update({"email": "[email protected]"}, email=None))   # Output: {'email': None}

settings = {"timeout": None}
print(settings.get("timeout", MISSING) is MISSING)  # Output: False
print(settings.get("retries", MISSING) is MISSING)  # Output: True

The first call leaves the address untouched and the second one clears it, which a default of None could not express. The same marker resolves the ambiguity of dict.get, where a key that is present with the value None and a key that is absent would otherwise produce the same result. The standard library relies on the technique in many places, for instance dataclasses.MISSING, which marks a field without a default, and the two-argument form of iter, which stops when a callable returns the given sentinel.

Readable and Durable Sentinels

The weakness of object() appears as soon as the marker leaves the function: its representation is an address such as <object object at 0x...>, which says nothing in a log or in the signature that help() displays, and it does not survive copying or pickling, because the copy is a new object. A small class with a __repr__ fixes the first problem but not the second. A single-member enumeration fixes both, because the members of an Enum are unique by construction and are restored by name when they are copied or unpickled.

import copy
import pickle
from enum import Enum

class _Missing(Enum):
    MISSING = "MISSING"

    def __repr__(self):
        return "<MISSING>"

MISSING = _Missing.MISSING
PLAIN = object()

print(repr(MISSING))                                  # Output: <MISSING>
print(copy.deepcopy(PLAIN) is PLAIN)                  # Output: False
print(pickle.loads(pickle.dumps(PLAIN)) is PLAIN)     # Output: False
print(copy.deepcopy(MISSING) is MISSING)              # Output: True
print(pickle.loads(pickle.dumps(MISSING)) is MISSING) # Output: True

The plain object loses its identity in both operations, so a configuration that is copied or sent to another process no longer recognizes its own marker. The enumeration keeps it, and it also gives type checkers a precise type: a parameter annotated as int | Literal[_Missing.MISSING] documents that only an integer or the marker is accepted. A sentinel is also the basis of the NOT_HANDLED marker described in the article devoted to the Chain of Responsibility, where a handler must signal that it declined a request without returning a value that could be a legitimate result.

Known Bugs: Pitfalls of Sentinel Values

A sentinel is correct only while its identity is preserved and checked, so its errors come from operations that create new objects or that compare by value. Six pitfalls are distinguished, which are the following:

  1. Comparing with ==. An object whose __eq__ always returns True is equal to any sentinel, whereas is cannot be overridden and compares identity alone.
  2. Copying and pickling object(). Both operations create a new instance, so the marker is no longer recognized after a copy, a pickle round trip or a transfer to another process.
  3. Uninformative representation. An object() sentinel appears as a memory address in logs, error messages and help() signatures.
  4. Testing truthiness. The sentinel is truthy, so a test such as if not value neither detects it nor separates it from 0, "" or None.
  5. Duplicated definitions. Defining the marker in two modules, or redefining it when a module is reloaded, creates two objects that do not recognize each other.
  6. Leaking the sentinel. Returning the marker to callers makes it part of the public interface, which then needs documentation, a type and a stable name.

The first pitfall is reproduced in the following example.

MISSING = object()

class Anything:
    def __eq__(self, other):
        return True

value = Anything()
print(value == MISSING, value is MISSING)  # Output: True False

The comparison with == reports that an ordinary argument is the marker, and a function written that way would ignore it. The identity check gives the correct answer, and it is also the cheaper operation, because it compares two references without calling any method. Since a sentinel must be the same object everywhere, it can also be created as a guaranteed single instance, a technique examined in the article devoted to __new__; for most code, however, a module-level enumeration member is simpler. At the date of this article, PEP 661 proposed a standard sentinel built-in that would address the representation, the pickling and the typing of markers, but it had not yet been accepted, so the techniques above were the available ones.

Choosing a Default Marker

Consequently, the right marker depends on whether None is a meaningful value and on how far the marker travels, as the following table summarizes.

Situation Recommended approach
None is never a meaningful argument A default of None
None is meaningful; marker stays inside one module MISSING = object() checked with is
Marker appears in logs or help() output A small class with __repr__, or an Enum member
Marker is copied, pickled or sent to other processes A single-member Enum
Marker appears in type annotations Literal of a single-member Enum
A value that must behave like a real object A dedicated null object instead of a marker
Field defaults in data classes dataclasses.field, which uses dataclasses.MISSING internally

Conclusion

It is concluded that a sentinel is a unique object that lets a function tell an omitted argument from any value, None included, that it must be checked with is, and that object() suffices inside a module while a single-member enumeration survives copying, pickling and type checking. This magic depends on preserving the identity of the marker, as the data classes described in the article devoted to data classes do with dataclasses.MISSING. Replacing a marker that is only compared with an object that behaves like a real one, so that callers need no special case at all, is the purpose of the Null Object pattern, which is developed in a future article of this series.