This guide explains Sentinel Objects: Introduction to the Built-In sentinel Type through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
Python introduces a built-in sentinel type for unique marker objects that distinguish “no value was supplied” from a valid supplied value such as None. A sentinel should be compared by identity.
When You Would Use This
An optional update function must know whether None was explicitly requested or no argument was passed.
Step-by-Step Example
MISSING = sentinel("MISSING")
def choose_message(message=MISSING):
if message is MISSING:
return "No message provided"
if message is None:
return "Message cleared"
return message
print(choose_message())
print(choose_message(None))
print(choose_message("Ready"))
How the Example Works
The identity comparison recognizes the marker reliably. Passing None triggers a different branch from leaving the argument out. This example requires Python; Python 3.13 cannot parse or execute the built-in sentinel name without an alternative definition.
Important Details
A sentinel is a dedicated marker, not text or a number. Use it sparingly when a normal default value is sufficient.
Try It Yourself
Add a fourth call that passes an empty string and verify that it remains distinguishable from omission.
Common Beginner Mistakes
- Using
Noneas both a legitimate value and an omitted-argument marker. - Testing sentinel equality instead of object identity.
- Expecting a named sentinel to behave like an empty string or a
Falsevalue.
Key Takeaways
- Python introduces a built-in
sentineltype for unique marker objects that distinguish “no value was supplied” from a valid supplied value such asNone. - The identity comparison recognizes the marker reliably.
- Avoid this mistake: Using
Noneas both a legitimate value and an omitted-argument marker.