Python developers often need a special value to represent something that is missing, not provided, or not yet initialized. For example, a function may need to distinguish between an argument that was not supplied and an argument that was explicitly set to None.
A common solution is to create a sentinel object. Developers have traditionally used object(), custom classes, or module-level constants for this purpose.
Python 3.15 makes this approach easier with a new built-in sentinel type. It introduces the sentinel() constructor, which creates a unique object with a meaningful name and a clear representation.
The new feature is based on PEP 661 and addresses several limitations of older sentinel implementations. Sentinel objects created with the built-in constructor preserve their identity when copied, support type expressions, and can be pickled when defined in an importable module under the appropriate name.
In this article, you will learn how sentinel objects work, why they are useful, how to replace traditional sentinel patterns, and how to use them in functions, APIs, configuration handling, and application development.
What Is a Sentinel Object?
A sentinel is a special object used to represent a condition that cannot be represented clearly by an ordinary value.
For example, consider a function that accepts an optional configuration value.
def get_timeout(timeout=None):
if timeout is None:
return 30
return timeout
This function uses None to indicate that no timeout was provided. However, what if the caller explicitly wants to set the timeout to None?
The function cannot distinguish between these two situations:
A sentinel solves this problem by providing a separate unique value.
Instead of using None for both situations, the function can use a dedicated object to indicate that the argument was not supplied.
MISSING = object()
def get_timeout(timeout=MISSING):
if timeout is MISSING:
return 30
return timeout
print(get_timeout())
print(get_timeout(None))
print(get_timeout(60))
The output is:
30
None
60
The function can now distinguish between a missing argument and an explicitly supplied None.
This pattern is useful in configuration systems, API update operations, database access layers, and application settings.
What Is New in Python 3.15?
Python 3.15 introduces a built-in sentinel type through PEP 661.
You can create a sentinel by calling the built-in sentinel() constructor.
MISSING = sentinel("MISSING")
print(MISSING)
Output:
MISSING
The name passed to sentinel() becomes the default representation of the object.
You no longer need to create a custom class or use an anonymous object merely to represent a missing value.
The new sentinel type provides several useful capabilities:
Creates a unique sentinel object.
Provides a meaningful representation.
Supports identity-based comparison.
Preserves identity during shallow and deep copying.
Supports the union operator in type expressions.
Supports pickling when defined in an appropriate importable scope.
Provides the name and module attributes.
The sentinel type is part of Python's built-in functionality, so it does not require an external package.
Creating Sentinel Objects With sentinel()
The simplest way to create a sentinel is to provide a name.
MISSING = sentinel("MISSING")
NOT_SET = sentinel("NOT_SET")
UNKNOWN = sentinel("UNKNOWN")
print(MISSING)
print(NOT_SET)
print(UNKNOWN)
Output:
MISSING
NOT_SET
UNKNOWN
Each call creates a new unique object.
For example:
FIRST = sentinel("FIRST")
SECOND = sentinel("SECOND")
print(FIRST is SECOND)
print(FIRST == SECOND)
Output:
False
False
Even if two sentinel objects have similar names, they are separate objects.
The built-in sentinel type does not support subclassing. Each sentinel is intended to be a unique value rather than a base class for custom object hierarchies.
Customizing the Sentinel Representation
By default, the name passed to sentinel() is used when the object is displayed.
Python 3.15 also allows developers to provide a custom representation through the repr argument.
MISSING = sentinel("MISSING", repr="<MISSING>")
NOT_AVAILABLE = sentinel(
"NOT_AVAILABLE",
repr="<NOT AVAILABLE>"
)
print(MISSING)
print(NOT_AVAILABLE)
Output:
<MISSING>
<NOT AVAILABLE>
This is useful when debugging applications because the sentinel's representation communicates its meaning clearly.
For example, a configuration system may use different sentinel values for missing, unresolved, and unavailable settings.
MISSING = sentinel("MISSING", repr="<MISSING>")
UNRESOLVED = sentinel("UNRESOLVED", repr="<UNRESOLVED>")
UNAVAILABLE = sentinel("UNAVAILABLE", repr="<UNAVAILABLE>")
These objects make debugging output easier to understand than anonymous object representations.
Distinguishing Missing Values From None
One of the most useful applications of sentinels is handling optional function arguments.
Consider a function that updates a customer's phone number.
The function needs to support three different operations:
Leave the existing phone number unchanged.
Explicitly remove the phone number by setting it to None.
Replace the phone number with a new value.
Using None as the default makes it difficult to distinguish between the first and second operations.
A sentinel provides a clear solution.
MISSING = sentinel("MISSING")
def update_customer(phone=MISSING):
if phone is MISSING:
print("Phone number remains unchanged")
elif phone is None:
print("Phone number removed")
else:
print(f"Phone number updated to {phone}")
update_customer()
update_customer(None)
update_customer("9876543210")
Output:
Phone number remains unchanged
Phone number removed
Phone number updated to 9876543210
This approach is especially useful in REST API update operations.
For example, an API may receive a partial update request where an omitted field means no change, while an explicit null value means that the existing value should be cleared.
A sentinel helps represent these different states in the application layer.
Using Sentinel Objects in Type Hints
Python 3.15 also improves how sentinel objects work with type expressions.
A sentinel can be used as part of a union type through the | operator.
Consider the following function:
MISSING = sentinel("MISSING")
def get_value(value: int | MISSING = MISSING):
if value is MISSING:
return 100
return value
print(get_value())
print(get_value(50))
The type expression int | MISSING describes a value that can be an integer or the MISSING sentinel.
This makes the function's expected input easier to understand.
Before this improvement, developers often used Any, object, or custom typing approaches to represent sentinel values in annotations.
The built-in sentinel provides a more direct way to express this pattern.
The annotation is still a static typing aid. It does not automatically validate incoming values at runtime.
For projects that use mypy or Pyright, verify that the installed type checker supports Python 3.15 sentinel type expressions.
Using Sentinel Objects With Configuration Settings
Configuration systems frequently need to distinguish between an unset value and a value explicitly set to None.
Consider an application that supports configurable retry limits.
MISSING = sentinel("MISSING")
def configure_retries(limit=MISSING):
if limit is MISSING:
limit = 3
if limit is None:
print("Retries are disabled")
return
print(f"Retry limit: {limit}")
configure_retries()
configure_retries(None)
configure_retries(5)
Output:
Retry limit: 3
Retries are disabled
Retry limit: 5
The sentinel makes the configuration behavior explicit.
This is useful when applications combine environment variables, configuration files, database settings, and default values.
For example, a missing configuration value may mean that the application should use a default. An explicit None may mean that a feature is disabled.
Using Sentinel Objects in API Update Operations
Partial update operations are another important use case.
Suppose an application allows users to update their profile information. A request may include a name, email, or phone number.
An omitted field should remain unchanged. An explicit None may indicate that a nullable field should be cleared.
MISSING = sentinel("MISSING")
def update_profile(
name: str | MISSING = MISSING,
email: str | MISSING = MISSING,
phone: str | None | MISSING = MISSING
):
updates = {}
if name is not MISSING:
updates["name"] = name
if email is not MISSING:
updates["email"] = email
if phone is not MISSING:
updates["phone"] = phone
return updates
print(update_profile(name="Alex"))
print(update_profile(phone=None))
print(update_profile(email="[email protected]"))
Output:
{'name': 'Alex'}
{'phone': None}
{'email': '[email protected]'}
The example demonstrates how a sentinel can help build an update dictionary without confusing omitted values with explicit null values.
In a real application, additional validation should be performed before applying these updates to a database.
Copying Sentinel Objects
A common problem with older sentinel implementations is that copying or deep-copying an object may create a different object.
This can break identity-based comparisons.
Python 3.15's built-in sentinel type avoids this problem.
Both shallow and deep copies return the original sentinel object.
import copy
MISSING = sentinel("MISSING")
shallow_copy = copy.copy(MISSING)
deep_copy = copy.deepcopy(MISSING)
print(shallow_copy is MISSING)
print(deep_copy is MISSING)
Output:
True
True
This behavior is important because sentinel objects are normally compared using is.
If copying created a different object, checks such as value is MISSING could fail unexpectedly.
The built-in implementation preserves the unique identity of the sentinel.
Pickling Sentinel Objects
Pickling is used to serialize Python objects so that they can be stored or transferred and reconstructed later.
Python 3.15 supports pickling sentinel objects when they are defined in an appropriate importable scope.
For reliable pickling, define the sentinel at the module level and use a variable name matching the name passed to sentinel().
For example, create a file named sentinels.py:
MISSING = sentinel("MISSING")
The sentinel is available as sentinels.MISSING.
You can then use it in another module:
import pickle
import sentinels
serialized = pickle.dumps(sentinels.MISSING)
restored = pickle.loads(serialized)
print(restored is sentinels.MISSING)
Output:
True
The identity is preserved after deserialization.
Python also supports sentinels defined in class scopes when their names match the qualified class attribute name.
import pickle
class ApplicationState:
MISSING = sentinel("ApplicationState.MISSING")
serialized = pickle.dumps(ApplicationState.MISSING)
restored = pickle.loads(serialized)
print(restored is ApplicationState.MISSING)
For function-local sentinels or other objects that are not accessible through an importable module and matching name, pickling is not supported.
This is an important consideration when designing applications that use multiprocessing, persistent caches, or serialized data.
Inspecting Sentinel Attributes
Python 3.15 sentinel objects expose two useful attributes:
The name attribute contains the sentinel's name.
The module attribute identifies the module associated with the sentinel.
MISSING = sentinel("MISSING")
print(MISSING.__name__)
print(MISSING.__module__)
For a sentinel defined in an importable module, these attributes help identify where the object belongs.
They are useful for debugging, introspection, and tools that inspect Python objects.
The module attribute is writable, so applications should avoid changing it casually, especially when pickling depends on the sentinel's module and name.
Comparing Python 3.15 Sentinels With Older Approaches
Before Python 3.15, developers generally created sentinel values using object(), custom classes, or third-party sentinel implementations.
Each approach has advantages and limitations.
Approach | Advantages | Limitations |
|---|
object() | Simple and built into Python | Anonymous representation and limited typing support |
Custom class | Can provide a meaningful representation | Requires additional code and careful copy/pickle behavior |
Enum member | Named and reusable | More structure than needed for a single sentinel |
Third-party sentinel implementation | May provide additional features | Requires an external dependency |
Built-in sentinel() | Named, unique, copy-stable, and supports type expressions | Available only in Python 3.15 and later |
For example, the traditional object() approach looks like this:
MISSING = object()
def get_setting(value=MISSING):
if value is MISSING:
return "Default setting"
return value
The Python 3.15 equivalent is:
MISSING = sentinel("MISSING")
def get_setting(value=MISSING):
if value is MISSING:
return "Default setting"
return value
The new approach is more readable because the sentinel has a meaningful representation.
For simple applications, object() may still be sufficient. However, the built-in sentinel is a better option when you need clear debugging output, stable identity during copying, type expressions, or supported pickling.
Best Practices for Using Sentinel Objects
Use Meaningful Names
Choose names that clearly describe the state represented by the sentinel.
For example, MISSING, NOT_SET, and UNAVAILABLE are easier to understand than VALUE1 or TEMP.
A meaningful name improves debugging and makes function signatures easier to read.
Use Identity Comparison
Sentinel objects should be compared with is and is not.
MISSING = sentinel("MISSING")
def process(value=MISSING):
if value is MISSING:
print("No value provided")
Avoid relying on equality comparisons when checking sentinel identity.
Define Reusable Sentinels at Module Level
If a sentinel is shared across multiple functions or modules, define it once in a common module and import it where needed.
This ensures that all parts of the application use the same object.
It is also important when pickling must preserve the sentinel's identity.
Do Not Use Sentinels for Ordinary Business Values
Sentinels are intended to represent special states such as missing or uninitialized values.
Do not create a separate sentinel for every normal application value when a regular enum, string, or data structure would be clearer.
Keep Runtime Validation Separate
Type annotations involving sentinels help describe expected values, but they do not automatically validate external input.
Validate data received from APIs, files, databases, and user interfaces before using it in application logic.
Consider Compatibility With Older Python Versions
The built-in sentinel constructor is available in Python 3.15 and later.
If your project supports Python 3.14 or earlier, you need a compatible alternative or a version-specific implementation.
Avoid introducing the built-in sentinel into shared libraries without considering the minimum Python version supported by your users.
Common Mistakes When Using Sentinels
Creating a New Sentinel for Every Comparison
This is incorrect:
def process(value):
if value is sentinel("MISSING"):
print("Missing")
Each call to sentinel() creates a new unique object. The comparison will not match a separately created sentinel.
Instead, create the sentinel once:
MISSING = sentinel("MISSING")
def process(value=MISSING):
if value is MISSING:
print("Missing")
Using Equality Instead of Identity
Although sentinel objects compare equal only to themselves, identity comparison is the intended way to check them.
Use:
if value is MISSING:
print("Missing value")
Assuming Every Sentinel Can Be Pickled
Sentinels defined inside functions or in locations that cannot be resolved through an importable module and matching name cannot be pickled reliably.
Define picklable sentinels at module level or in supported class scopes.
Assuming Sentinel Annotations Validate Input
An annotation such as int | MISSING describes the expected type to static analysis tools. It does not automatically reject an unexpected string or other value at runtime.
Use explicit validation when runtime guarantees are required.
Confusing Missing Values With None
None is a legitimate Python value. It should not automatically mean that an argument was omitted.
Use a sentinel when the application needs to distinguish between these states.
Advantages and Limitations of Python 3.15 Sentinel
Advantages | Limitations |
|---|
Creates unique and clearly named objects | Requires Python 3.15 or later |
Provides readable representations | Does not automatically validate function arguments |
Preserves identity during shallow and deep copying | Cannot be subclassed |
Supports union type expressions | Type checker support may vary |
Supports pickling in supported scopes | Function-local sentinels are not picklable |
Removes the need for many custom sentinel implementations | Requires careful naming and shared definitions |
Conclusion
Python 3.15's built-in sentinel type makes it easier to represent missing, unset, and special values in application code. It provides a standard alternative to anonymous object instances and custom sentinel classes.
The sentinel() constructor creates a unique object with a meaningful representation. Its identity remains stable during copying, it can be used in type expressions, and it supports pickling when defined in an appropriate importable scope.
Sentinels are especially useful for function defaults, configuration handling, partial API updates, and data-processing workflows where None is a valid value.
When adopting this feature, define reusable sentinels in a shared module, compare them with is, and validate external data separately. These practices help keep application behavior predictable while making missing-value handling easier to understand and maintain.
Join the conversation! Your thoughts help the community grow.