class Sentinel
Creates a unique sentinel object that can be used as a distinct marker value in code, similar to None but with custom identity and representation.
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/typing_extensions.py
4210 - 4245
moderate
Purpose
The Sentinel class provides a way to create unique singleton-like marker objects that can be used to represent special values (like 'missing', 'unset', 'default') in APIs where None might be a valid value. Each Sentinel instance is unique and can have a custom string representation. It supports type hinting integration (especially in Python 3.10+) and prevents pickling to maintain uniqueness across serialization boundaries.
Source Code
class Sentinel:
"""Create a unique sentinel object.
*name* should be the name of the variable to which the return value shall be assigned.
*repr*, if supplied, will be used for the repr of the sentinel object.
If not provided, "<name>" will be used.
"""
def __init__(
self,
name: str,
repr: typing.Optional[str] = None,
):
self._name = name
self._repr = repr if repr is not None else f'<{name}>'
def __repr__(self):
return self._repr
if sys.version_info < (3, 11):
# The presence of this method convinces typing._type_check
# that Sentinels are types.
def __call__(self, *args, **kwargs):
raise TypeError(f"{type(self).__name__!r} object is not callable")
# Breakpoint: https://github.com/python/cpython/pull/21515
if sys.version_info >= (3, 10):
def __or__(self, other):
return typing.Union[self, other]
def __ror__(self, other):
return typing.Union[other, self]
def __getstate__(self):
raise TypeError(f"Cannot pickle {type(self).__name__!r} object")
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
- | - |
Parameter Details
name: A string identifier for the sentinel object, typically matching the variable name it will be assigned to. This is used to generate the default repr if no custom repr is provided.
repr: Optional custom string representation for the sentinel object. If not provided, defaults to '<name>' format. This is what will be displayed when the sentinel is printed or converted to a string.
Return Value
Instantiation returns a Sentinel object that serves as a unique marker value. The object has a custom string representation and cannot be called, pickled, or used like a regular value. In Python 3.10+, it can be used in Union type expressions with the | operator.
Class Interface
Methods
__init__(self, name: str, repr: typing.Optional[str] = None)
Purpose: Initializes a new Sentinel object with a name and optional custom representation
Parameters:
name: String identifier for the sentinel, typically matching the variable namerepr: Optional custom string representation; defaults to '<name>' if not provided
Returns: None (constructor)
__repr__(self) -> str
Purpose: Returns the string representation of the sentinel object
Returns: The custom repr string set during initialization
__call__(self, *args, **kwargs)
Purpose: Prevents the sentinel from being called as a function; raises TypeError. Only present in Python < 3.11
Parameters:
args: Any positional arguments (ignored)kwargs: Any keyword arguments (ignored)
Returns: Never returns; always raises TypeError
__or__(self, other) -> typing.Union
Purpose: Enables using the | operator to create Union types with the sentinel. Only available in Python >= 3.10
Parameters:
other: The type to union with this sentinel
Returns: A typing.Union containing this sentinel and the other type
__ror__(self, other) -> typing.Union
Purpose: Enables using the | operator with the sentinel on the right side. Only available in Python >= 3.10
Parameters:
other: The type to union with this sentinel
Returns: A typing.Union containing the other type and this sentinel
__getstate__(self)
Purpose: Prevents pickling of sentinel objects to maintain uniqueness across serialization
Returns: Never returns; always raises TypeError
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
_name |
str | Stores the name identifier of the sentinel object | instance |
_repr |
str | Stores the string representation that will be returned by __repr__ | instance |
Dependencies
typingsys
Required Imports
import typing
import sys
Usage Example
# Create sentinel values for API parameters
import typing
import sys
class Sentinel:
def __init__(self, name: str, repr: typing.Optional[str] = None):
self._name = name
self._repr = repr if repr is not None else f'<{name}>'
def __repr__(self):
return self._repr
if sys.version_info < (3, 11):
def __call__(self, *args, **kwargs):
raise TypeError(f"{type(self).__name__!r} object is not callable")
if sys.version_info >= (3, 10):
def __or__(self, other):
return typing.Union[self, other]
def __ror__(self, other):
return typing.Union[other, self]
def __getstate__(self):
raise TypeError(f"Cannot pickle {type(self).__name__!r} object")
# Create unique sentinel values
MISSING = Sentinel('MISSING')
UNSET = Sentinel('UNSET', repr='<parameter not set>')
# Use in function signatures
def process_data(value=MISSING):
if value is MISSING:
print("No value provided")
else:
print(f"Processing: {value}")
process_data() # No value provided
process_data(None) # Processing: None
process_data(42) # Processing: 42
# Check identity
print(MISSING) # <MISSING>
print(UNSET) # <parameter not set>
print(MISSING is MISSING) # True
print(MISSING == MISSING) # False (different identity)
# Python 3.10+ type hint usage
if sys.version_info >= (3, 10):
def typed_function(param: str | MISSING = MISSING) -> str:
if param is MISSING:
return "default"
return param
Best Practices
- Always use identity checks (is/is not) rather than equality checks (==/!=) when comparing with sentinel values
- Assign sentinel instances to module-level constants with descriptive UPPERCASE names
- Use sentinels when None is a valid value in your API and you need to distinguish between 'not provided' and 'explicitly set to None'
- Do not attempt to pickle or serialize sentinel objects - they are designed to maintain unique identity within a single Python process
- Do not call sentinel objects as functions - they will raise TypeError
- In Python 3.10+, sentinels can be used in Union type expressions with the | operator for better type hinting
- The sentinel's repr should be descriptive enough to understand its purpose when debugging
- Create sentinel instances at module level, not inside functions, to ensure they remain unique throughout the program's lifetime
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class _Sentinel 83.5% similar
-
class _EllipsisDummy 45.9% similar
-
class SharedObjectType 41.1% similar
-
class WellknownListName 39.7% similar
-
class AttachmentType_v1 32.5% similar