sentinel
raw JSON → 1.0.0 verified Mon Apr 27 auth: no python
Create sentinel objects, akin to None, NotImplemented, Ellipsis. Provides a simple way to define unique sentinel values for signaling special conditions (e.g., default arguments, missing data). Current version: 1.0.0. Release cadence: infrequent, stable.
pip install sentinel Common errors
error ImportError: cannot import name 'sentinel' from 'sentinel' ↓
cause Attempting to import the lowercase 'sentinel' instead of the class 'Sentinel'.
fix
Use: from sentinel import Sentinel
error AttributeError: module 'sentinel' has no attribute 'Sentinel' ↓
cause The library may not be installed correctly, or an older version without the Sentinel class is installed. (Library has always had Sentinel class, but check version.)
fix
Run: pip install --upgrade sentinel
error PicklingError: Can't pickle <class 'sentinel.Sentinel'>: it's not found as sentinel.Sentinel ↓
cause Trying to pickle a sentinel instance without proper __reduce__ implementation.
fix
Define a custom pickle behavior: See https://github.com/eddieantonio/sentinel#pickling
Warnings
gotcha Sentinel instances are not singletons by default; each call to Sentinel('name') creates a new instance. Use a module-level constant to maintain identity. ↓
fix Always assign the sentinel to a module-level variable (e.g., _MISSING = Sentinel('MISSING')) and import that variable.
gotcha Sentinel objects cannot be pickled by default. Attempting to pickle a sentinel will raise a PicklingError. ↓
fix If pickling is needed, use sentinel's __reduce__ method or define a custom sentinel class.
gotcha Sentinel instances compare by identity, not value. Using == may give unexpected results if the sentinel is not the exact same object. ↓
fix Always use 'is' for comparison, not '=='.
Imports
- Sentinel wrong
from sentinel import sentinelcorrectfrom sentinel import Sentinel
Quickstart
from sentinel import Sentinel
# Create a unique sentinel
NotGiven = Sentinel('NotGiven')
def get_value(key, default=NotGiven):
if default is NotGiven:
print('No default provided')
else:
print(f'Default is {default}')
get_value('foo')
get_value('foo', default='bar')