Python’s None often carries several meanings: a value is absent, a setting is unset, an operation failed, or the value itself is genuinely None. That overlap causes bugs and awkward APIs. A cache cannot distinguish a missing key from one storing None; a configuration update cannot tell whether timeout=None means “disable the timeout” or “leave it unchanged”; and a function that catches TimeoutError and returns None hides whether it succeeded. Sentinel values solve the problem by using a distinct marker that cannot be confused with valid data. Python already uses sentinels: Ellipsis has roles in slicing and stubs, while NotImplemented lets operators defer to another implementation. Pydantic’s MISSING similarly distinguishes an omitted field from one explicitly set to null.
Creating custom sentinels used to involve trade-offs. The common object() marker works at runtime but does not support reliable type narrowing; TypeIs guards, string literals, and one-member Enums each have drawbacks, and copying or pickling can undermine identity checks. PEP 661, which was initially deferred and then accepted nine days later, introduces a standard sentinel() built-in in Python 3.15. A sentinel can distinguish “no update” from “delete this value” and an actual value, while allowing type checkers to narrow the remaining type. Older versions can use typing_extensions, though checker support may vary. The practical advice is to identify what None is meant to express, use a library’s existing sentinel where possible, and replace improvised markers with the built-in when available.
Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.