| 1 |
"""Sentinel class.""" |
| 2 |
|
| 3 |
__all__ = ('Sentinel', 'NOT_SET') |
| 4 |
|
| 5 |
|
| 6 |
class Sentinel: |
| 7 |
"""A class to create sentinel objects. |
| 8 |
|
| 9 |
The benefits vs. object() are a good repr it is picklable. |
| 10 |
|
| 11 |
Inspired by https://pypi.org/project/sentinels/ |
| 12 |
""" |
| 13 |
|
| 14 |
_registry = {} |
| 15 |
|
| 16 |
def __getnewargs__(self): |
| 17 |
return self._name, |
| 18 |
|
| 19 |
def __new__(cls, _name): |
| 20 |
"""Find the Sentinel object with name or create a new one.""" |
| 21 |
try: |
| 22 |
return cls._registry[_name] |
| 23 |
except KeyError: |
| 24 |
new = super(Sentinel, cls).__new__(cls) |
| 25 |
cls._registry[_name] = new |
| 26 |
return new |
| 27 |
|
| 28 |
def __init__(self, name): |
| 29 |
super(Sentinel, self).__init__() |
| 30 |
self._name = name |
| 31 |
|
| 32 |
def __repr__(self): |
| 33 |
return '<%s>' % self._name |
| 34 |
|
| 35 |
def __bool__(self): |
| 36 |
return False |
| 37 |
|
| 38 |
def __eq__(self, other): |
| 39 |
if other.__class__ == self.__class__: |
| 40 |
return self._name == other._name |
| 41 |
return False |
| 42 |
|
| 43 |
|
| 44 |
NOT_SET = Sentinel('not_set') |