In Python, developers often set a parameter's default value to None—until None itself becomes a meaningful input. For example, updating a student profile might need to distinguish between "keep the existing nickname" and "clear the nickname to None." Starting in Python 3.15, PEP 661 adds a built-in sentinel() callable so you can define clean, readable, type-safe sentinel objects without custom classes or imports.
MISSING = sentinel("MISSING") (Argument omitted) • None (Explicitly clear field) • "Maya" (Set new value)
Why Not Use object()?
Previously, programmers created sentinels with _MISSING = object(). That worked at runtime, but printed ugly addresses like <object object at 0x...> in debugging logs, did not integrate smoothly with static type hints, and failed identity checks after pickling or copying. Built-in sentinel("MISSING") solves all three issues.
Try a Student Profile Update Example
Because sentinel is a built-in in Python 3.15, you can call it directly at module level without importing a module:
from typing import Literal
MISSING = sentinel("MISSING")
def update_student_profile(
name: str,
nickname: str | None | Literal[MISSING] = MISSING,
) -> str:
if nickname is MISSING:
return f"{name}: kept existing nickname"
if nickname is None:
return f"{name}: cleared nickname"
return f"{name}: updated nickname to {nickname}"
print(update_student_profile("Aarav"))
print(update_student_profile("Aarav", None))
print(update_student_profile("Aarav", "Ari"))
print(repr(MISSING))
Two Important Rules to Know
- Always compare with
is: Writeif nickname is MISSING:rather than==to test exact singleton identity. - Define sentinels at module top level:
sentinel()records the defining module automatically so pickling and unpickling can import the exact same singleton object by name.
Practice
- Add a
bioparameter defaulting toMISSINGinupdate_student_profileso callers can update bio and nickname independently. - Print
MISSINGinside a function signature usinghelp(update_student_profile)and compare its readable name againstobject(). - Test creating two sentinels with different names and verify
MISSING is not sentinel("OTHER").
Continue learning: Python Tutorial for Beginners: Complete Learning Path.
References: Python 3.15 Documentation; PEP 661 Sentinel Values.
No comments:
Post a Comment
Please do not enter any spam link in the comment box.