PEP 661: Add bool value to reference impl and examples (#4051)

This commit is contained in:
Tal Einat 2024-10-14 00:02:00 +03:00 committed by GitHub
parent 9af6b95a52
commit 7efe235d84
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 10 additions and 2 deletions

View File

@ -154,7 +154,10 @@ boolean value, and the name of its module::
>>> MISSING = Sentinel('MISSING', repr='mymodule.MISSING')
>>> MISSING
mymodule.MISSING
>>> MEGA = Sentinel('MEGA', repr='<MEGA>', module_name='mymodule')
>>> MEGA = Sentinel('MEGA',
repr='<MEGA>',
bool_value=False,
module_name='mymodule')
<MEGA>
Checking if a value is such a sentinel *should* be done using the ``is``
@ -235,9 +238,10 @@ simplified version follows::
class Sentinel:
"""Unique sentinel values."""
def __new__(cls, name, repr=None, module_name=None):
def __new__(cls, name, repr=None, bool_value=True, module_name=None):
name = str(name)
repr = str(repr) if repr else f'<{name.split(".")[-1]}>'
bool_value = bool(bool_value)
if module_name is None:
try:
module_name = \
@ -254,6 +258,7 @@ simplified version follows::
sentinel = super().__new__(cls)
sentinel._name = name
sentinel._repr = repr
sentinel._bool_value = bool_value
sentinel._module_name = module_name
return _registry.setdefault(registry_key, sentinel)
@ -261,6 +266,9 @@ simplified version follows::
def __repr__(self):
return self._repr
def __bool__(self):
return self._bool_value
def __reduce__(self):
return (
self.__class__,