Core¶
typed_sentinels._core
¶
Classes¶
Sentinel
¶
Statically-typed sentinel object with singleton qualities.
Sentinel instances provide unique placeholder objects that maintain singleton behavior for a given type. They are
particularly well-suited for use with types requiring parameters which are only available at runtime, where creating
a default instance of the type may not be possible in advance, but the structural contract of the type is otherwise
guaranteed to be fulfilled once present.
Examples:
Basic usage:
from typed_sentinels import Sentinel
SNTL = Sentinel() # Same as `typing.Any`
BYTES_SNTL = Sentinel(bytes) # Same as `bytes`
TUPLE_SNTL = Sentinel[tuple[str, ...]]() # Same as `tuple[str, ...]`
assert SNTL is not BYTES_SNTL # True
assert Sentinel() is SNTL # True
assert Sentinel(tuple[str, ...]) is TUPLE_SNTL # True
assert Sentinel(tuple[bytes, ...]) is not TUPLE_SNTL # True
To the type-checker, Sentinel objects are indistinguishable from an instance of the assigned type:
from typing import reveal_type
class Custom:
def __init__(self, req_str: str, req_bytes: bytes) -> None:
if not req_str or not req_bytes:
raise ValueError
CUSTOM_SNTL = Sentinel(Custom)
reveal_type(CUSTOM_SNTL) # Revealed type is `Custom` -> Runtime type is `Sentinel`
def example_func(b: bytes = BYTES_SNTL, c: Custom = CUSTOM_SNTL) -> Any:
if not b:
print('Sentinels are falsy so this check works')
if not c: ...
This even works for complex types like Callable:
CALLABLE_SNTL = Sentinel[Callable[..., str]]()
reveal_type(CALLABLE_SNTL) # Type of "CALLABLE_SNTL" is "(...) -> str"
Attributes¶
Functions¶
__new__
¶
Create or retrieve a Sentinel instance for the given hint type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hint
|
T
|
Type that this |
_OBJECT
|
Returns:
| Type | Description |
|---|---|
T
|
|
Raises:
| Type | Description |
|---|---|
InvalidHintError
|
If |
SubscriptedTypeError
|
If provided both a subscripted type parameter and a direct type argument and the types should differ (e.g.,
|
Source code in src/typed_sentinels/_core.py
__class_getitem__
¶
__getitem__
¶
__call__
¶
__str__
¶
Source code in src/typed_sentinels/_core.py
__repr__
¶
__hash__
¶
__bool__
¶
__eq__
¶
__copy__
¶
__deepcopy__
¶
__reduce__
¶
__reduce_ex__
¶
__setattr__
¶
Functions¶
is_sentinel
¶
Return True if obj is a Sentinel instance, optionally further narrowed to be of typ type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
Possible |
required |
typ
|
T | None
|
Optional type to be used to further narrow the type of the |
None
|
Returns:
| Type | Description |
|---|---|
TypeGuard[Sentinel]
|
|