Python Glossary Русский

Python 3.15+Built-in functionsterm

sentinel()

objects

Creates a unique marker object with a readable repr, e.g. “no value given” when None itself is a valid value.

Syntax

sentinel(name, /, *, repr=None)

The classic substitute is MISSING = object(): unique, but in debugging it prints as <object object at 0x7f...>, does not copy meaningfully and cannot be used in an annotation. sentinel('MISSING') prints as MISSING, survives copy and deepcopy (the same object comes back), pickles when it lives in a module under the same name, and can appear in an annotation: int | MISSING. Compare it with is, not ==; it is always truthy, so a check like if value: will not tell it apart — write if value is MISSING. Subclassing sentinel is not allowed. By convention the variable name matches the marker's name.

Examples

MISSING = sentinel('MISSING')
def get(d, key, default=MISSING):
    if key in d:
        return d[key]
    if default is MISSING:
        raise KeyError(key)
    return default
print(get({'a': None}, 'a'))  # → None — None здесь законное значение
print(get({}, 'b', 0))  # → 0
print(MISSING)  # → MISSING
import copy
MISSING = sentinel('MISSING')
print(copy.deepcopy(MISSING) is MISSING)  # → True
print(bool(MISSING))  # → True — проверяйте через is, а не через if

See also

Open in the full glossarydocs.python.orgReport an inaccuracy