typed-sentinels 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- typed_sentinels-0.1.0/PKG-INFO +100 -0
- typed_sentinels-0.1.0/README.md +88 -0
- typed_sentinels-0.1.0/pyproject.toml +174 -0
- typed_sentinels-0.1.0/src/typed_sentinels/__init__.py +30 -0
- typed_sentinels-0.1.0/src/typed_sentinels/_core.py +246 -0
- typed_sentinels-0.1.0/src/typed_sentinels/_exceptions.py +42 -0
- typed_sentinels-0.1.0/src/typed_sentinels/py.typed +0 -0
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: typed-sentinels
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Statically-typed sentinel objects with singleton qualities.
|
|
5
|
+
Author: Alchemyst
|
|
6
|
+
Author-email: Alchemyst <alchemyst@alchemyst.dev>
|
|
7
|
+
Requires-Python: >=3.12
|
|
8
|
+
Project-URL: documentation, https://typed-sentinels.blockmage.dev
|
|
9
|
+
Project-URL: homepage, https://github.com/blockmage/typed_sentinels
|
|
10
|
+
Project-URL: repository, https://github.com/blockmage/typed_sentinels
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# typed-sentinels
|
|
14
|
+
|
|
15
|
+
Statically-typed sentinel objects with singleton qualities (for Python 3.12+).
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pip install typed-sentinels
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Quick Start
|
|
24
|
+
|
|
25
|
+
- `Sentinel` instances are useful for creating unique, type-annotated placeholders, typically used
|
|
26
|
+
when a default value other than `None` is desirable. Only a single instance of `Sentinel` may
|
|
27
|
+
exist for a given type.
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
from typed_sentinels import Sentinel
|
|
31
|
+
|
|
32
|
+
# Annotate with the type the sentinel should appear to be to the type-checker
|
|
33
|
+
SENTINEL_STR: str = Sentinel(str)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def process_data(value: str = SENTINEL_STR) -> str:
|
|
37
|
+
# Sentinels are always falsy
|
|
38
|
+
if not value:
|
|
39
|
+
return 'No value provided'
|
|
40
|
+
return f'Processing: {value}'
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# Type-safe usage
|
|
44
|
+
result = process_data() # "No value provided"
|
|
45
|
+
result = process_data('demo123') # "Processing: demo123"
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
- The `Sentinel` class is particularly well-suited for use with types requiring parameters which are
|
|
49
|
+
only available at runtime, where creating a default instance of the type may not be possible in
|
|
50
|
+
advance, but the structural contract of the type is otherwise guaranteed to be fulfilled once present.
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from typed_sentinels import Sentinel
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class Custom:
|
|
57
|
+
@property
|
|
58
|
+
def value(self) -> str:
|
|
59
|
+
return self._value
|
|
60
|
+
|
|
61
|
+
def __init__(self, required: str, /) -> None:
|
|
62
|
+
self._value = required
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# Appears to the type-checker as an instance of `Custom`
|
|
66
|
+
CUSTOM: Custom = Sentinel(Custom)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def func(c: Custom = CUSTOM) -> str:
|
|
70
|
+
if c is not CUSTOM:
|
|
71
|
+
return c.value
|
|
72
|
+
return 'c was not provided'
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
- `Sentinel` instances have singleton qualities, but remain distinct as specific to the type they represent:
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
S1 = Sentinel(dict[str, Any])
|
|
79
|
+
S2 = Sentinel(dict[str, Any])
|
|
80
|
+
S3 = Sentinel(dict[str, bytes])
|
|
81
|
+
|
|
82
|
+
assert S1 is S2 # True
|
|
83
|
+
assert S2 is not S3 # True
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
- In the simplest form, supposing you don't want or need a distinct instance for different types,
|
|
87
|
+
you could use the `Sentinel` without parameterization or arguments, and the type-checker will
|
|
88
|
+
still be happy:
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
class Custom:
|
|
92
|
+
def __init__(self, arg1: str, arg2: int, arg3: bool) -> None: ...
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
# This appears to the type-checker as an actual instance of Custom
|
|
96
|
+
CUSTOM: Custom = Sentinel()
|
|
97
|
+
reveal_type(CUSTOM) # Runtime type is 'Sentinel'
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+

|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# typed-sentinels
|
|
2
|
+
|
|
3
|
+
Statically-typed sentinel objects with singleton qualities (for Python 3.12+).
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install typed-sentinels
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick Start
|
|
12
|
+
|
|
13
|
+
- `Sentinel` instances are useful for creating unique, type-annotated placeholders, typically used
|
|
14
|
+
when a default value other than `None` is desirable. Only a single instance of `Sentinel` may
|
|
15
|
+
exist for a given type.
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from typed_sentinels import Sentinel
|
|
19
|
+
|
|
20
|
+
# Annotate with the type the sentinel should appear to be to the type-checker
|
|
21
|
+
SENTINEL_STR: str = Sentinel(str)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def process_data(value: str = SENTINEL_STR) -> str:
|
|
25
|
+
# Sentinels are always falsy
|
|
26
|
+
if not value:
|
|
27
|
+
return 'No value provided'
|
|
28
|
+
return f'Processing: {value}'
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# Type-safe usage
|
|
32
|
+
result = process_data() # "No value provided"
|
|
33
|
+
result = process_data('demo123') # "Processing: demo123"
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
- The `Sentinel` class is particularly well-suited for use with types requiring parameters which are
|
|
37
|
+
only available at runtime, where creating a default instance of the type may not be possible in
|
|
38
|
+
advance, but the structural contract of the type is otherwise guaranteed to be fulfilled once present.
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
from typed_sentinels import Sentinel
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Custom:
|
|
45
|
+
@property
|
|
46
|
+
def value(self) -> str:
|
|
47
|
+
return self._value
|
|
48
|
+
|
|
49
|
+
def __init__(self, required: str, /) -> None:
|
|
50
|
+
self._value = required
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# Appears to the type-checker as an instance of `Custom`
|
|
54
|
+
CUSTOM: Custom = Sentinel(Custom)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def func(c: Custom = CUSTOM) -> str:
|
|
58
|
+
if c is not CUSTOM:
|
|
59
|
+
return c.value
|
|
60
|
+
return 'c was not provided'
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
- `Sentinel` instances have singleton qualities, but remain distinct as specific to the type they represent:
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
S1 = Sentinel(dict[str, Any])
|
|
67
|
+
S2 = Sentinel(dict[str, Any])
|
|
68
|
+
S3 = Sentinel(dict[str, bytes])
|
|
69
|
+
|
|
70
|
+
assert S1 is S2 # True
|
|
71
|
+
assert S2 is not S3 # True
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
- In the simplest form, supposing you don't want or need a distinct instance for different types,
|
|
75
|
+
you could use the `Sentinel` without parameterization or arguments, and the type-checker will
|
|
76
|
+
still be happy:
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
class Custom:
|
|
80
|
+
def __init__(self, arg1: str, arg2: int, arg3: bool) -> None: ...
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# This appears to the type-checker as an actual instance of Custom
|
|
84
|
+
CUSTOM: Custom = Sentinel()
|
|
85
|
+
reveal_type(CUSTOM) # Runtime type is 'Sentinel'
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+

|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
[project.urls]
|
|
2
|
+
documentation = "https://typed-sentinels.blockmage.dev"
|
|
3
|
+
homepage = "https://github.com/blockmage/typed_sentinels"
|
|
4
|
+
repository = "https://github.com/blockmage/typed_sentinels"
|
|
5
|
+
|
|
6
|
+
[project]
|
|
7
|
+
description = "Statically-typed sentinel objects with singleton qualities."
|
|
8
|
+
name = "typed-sentinels"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.12"
|
|
11
|
+
version = "0.1.0"
|
|
12
|
+
|
|
13
|
+
authors = [
|
|
14
|
+
{ email = "alchemyst@alchemyst.dev", name = "Alchemyst" },
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
dependencies = [ ]
|
|
18
|
+
|
|
19
|
+
[dependency-groups]
|
|
20
|
+
dev = [
|
|
21
|
+
"commitizen>=4.8.3",
|
|
22
|
+
"coverage>=7.9.1",
|
|
23
|
+
"docformatter>=1.7.7",
|
|
24
|
+
"mkdocs-material>=9.6.15",
|
|
25
|
+
"mkdocs>=1.6.1",
|
|
26
|
+
"mkdocstrings[python]>=0.30.0",
|
|
27
|
+
"pre-commit>=4.2.0",
|
|
28
|
+
"pyright>=1.1.402",
|
|
29
|
+
"pytest-cov>=6.2.1",
|
|
30
|
+
"pytest>=8.4.1",
|
|
31
|
+
"pytest>=8.4.1",
|
|
32
|
+
"ruff>=0.12.1",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
# -------------------------------- build system --------------------------------
|
|
36
|
+
[build-system]
|
|
37
|
+
build-backend = "uv_build"
|
|
38
|
+
requires = [ "uv_build>=0.8.11,<0.9.0" ]
|
|
39
|
+
|
|
40
|
+
# ------------------------------- tool: coverage -------------------------------
|
|
41
|
+
[tool.coverage.report]
|
|
42
|
+
skip_empty = "true"
|
|
43
|
+
|
|
44
|
+
exclude_also = [
|
|
45
|
+
"\\.\\.\\.",
|
|
46
|
+
"cast(.*)",
|
|
47
|
+
"if TYPE_CHECKING",
|
|
48
|
+
"if __name__ == .__main__.:",
|
|
49
|
+
"msg =.*",
|
|
50
|
+
"raise AssertionError",
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
[tool.coverage.html]
|
|
54
|
+
directory = "reports/coverage/html"
|
|
55
|
+
|
|
56
|
+
# ----------------------------- tool: docformatter -----------------------------
|
|
57
|
+
[tool.docformatter]
|
|
58
|
+
blank = false
|
|
59
|
+
force = false
|
|
60
|
+
make-summary-multi-line = false
|
|
61
|
+
pre-summary-newline = false
|
|
62
|
+
recursive = true
|
|
63
|
+
style = "numpy"
|
|
64
|
+
wrap-descriptions = 120
|
|
65
|
+
wrap-summaries = 120
|
|
66
|
+
|
|
67
|
+
# ------------------------------- tool: pyright --------------------------------
|
|
68
|
+
[tool.pyright]
|
|
69
|
+
include = [ ".", "src" ]
|
|
70
|
+
pythonPlatform = "Linux"
|
|
71
|
+
pythonVersion = "3.12"
|
|
72
|
+
stubPath = "./stubs"
|
|
73
|
+
typeCheckingMode = "standard"
|
|
74
|
+
venv = ".venv"
|
|
75
|
+
venvPath = "."
|
|
76
|
+
|
|
77
|
+
analyzeUnannotatedFunctions = true
|
|
78
|
+
deprecateTypingAliases = true
|
|
79
|
+
strictDictionaryInference = false
|
|
80
|
+
strictListInference = true
|
|
81
|
+
strictSetInference = true
|
|
82
|
+
useLibraryCodeForTypes = true
|
|
83
|
+
|
|
84
|
+
executionEnvironments = [
|
|
85
|
+
{ pythonVersion = "3.12", root = "." },
|
|
86
|
+
]
|
|
87
|
+
|
|
88
|
+
# -------------------------------- tool: pytest --------------------------------
|
|
89
|
+
[tool.pytest.ini_options]
|
|
90
|
+
addopts = [
|
|
91
|
+
"--cov-report=html",
|
|
92
|
+
"--cov=typed_sentinels",
|
|
93
|
+
"--import-mode=importlib",
|
|
94
|
+
"-s",
|
|
95
|
+
"-vv",
|
|
96
|
+
]
|
|
97
|
+
|
|
98
|
+
norecursedirs = [ ".venv" ]
|
|
99
|
+
python_files = [ "test_*.py" ]
|
|
100
|
+
testpaths = [ "." ]
|
|
101
|
+
|
|
102
|
+
# --------------------------------- tool: ruff ---------------------------------
|
|
103
|
+
[tool.ruff]
|
|
104
|
+
exclude = [ ]
|
|
105
|
+
force-exclude = true
|
|
106
|
+
indent-width = 4
|
|
107
|
+
line-length = 120
|
|
108
|
+
respect-gitignore = true
|
|
109
|
+
target-version = "py312"
|
|
110
|
+
unsafe-fixes = true
|
|
111
|
+
|
|
112
|
+
[tool.ruff.format]
|
|
113
|
+
docstring-code-format = true
|
|
114
|
+
docstring-code-line-length = "dynamic"
|
|
115
|
+
indent-style = "space"
|
|
116
|
+
line-ending = "lf"
|
|
117
|
+
quote-style = "single"
|
|
118
|
+
skip-magic-trailing-comma = false
|
|
119
|
+
|
|
120
|
+
[tool.ruff.lint]
|
|
121
|
+
fixable = [ "ALL" ]
|
|
122
|
+
select = [ "ALL" ]
|
|
123
|
+
unfixable = [ ]
|
|
124
|
+
|
|
125
|
+
ignore = [
|
|
126
|
+
"ANN401", # any-type
|
|
127
|
+
"COM", # flake8-commas
|
|
128
|
+
"D1", # undocumented-{module,class,method,...}
|
|
129
|
+
"INP001", # implicit-namespace-package
|
|
130
|
+
"SIM102", # collapsible-if
|
|
131
|
+
"SLF001", # private-member-access
|
|
132
|
+
"T201", # print
|
|
133
|
+
]
|
|
134
|
+
|
|
135
|
+
[tool.ruff.lint.per-file-ignores]
|
|
136
|
+
"*test*" = [ "ANN", "D", "N", "Q", "S" ]
|
|
137
|
+
|
|
138
|
+
[tool.ruff.lint.isort]
|
|
139
|
+
known-first-party = [ ]
|
|
140
|
+
|
|
141
|
+
[tool.ruff.lint.flake8-unused-arguments]
|
|
142
|
+
ignore-variadic-names = true
|
|
143
|
+
|
|
144
|
+
[tool.ruff.lint.flake8-annotations]
|
|
145
|
+
allow-star-arg-any = true
|
|
146
|
+
|
|
147
|
+
[tool.ruff.lint.flake8-quotes]
|
|
148
|
+
inline-quotes = "single"
|
|
149
|
+
|
|
150
|
+
[tool.ruff.lint.pydocstyle]
|
|
151
|
+
convention = "numpy"
|
|
152
|
+
|
|
153
|
+
[tool.ruff.lint.pylint]
|
|
154
|
+
allow-magic-value-types = [ "float", "int", "str" ]
|
|
155
|
+
max-args = 20
|
|
156
|
+
max-bool-expr = 10
|
|
157
|
+
max-branches = 20
|
|
158
|
+
max-locals = 15
|
|
159
|
+
max-nested-blocks = 10
|
|
160
|
+
max-positional-args = 20
|
|
161
|
+
max-returns = 10
|
|
162
|
+
max-statements = 75
|
|
163
|
+
|
|
164
|
+
[tool.ruff.lint.flake8-bugbear]
|
|
165
|
+
extend-immutable-calls = [ ]
|
|
166
|
+
|
|
167
|
+
# ---------------------------------- tool: uv ----------------------------------
|
|
168
|
+
[tool.uv]
|
|
169
|
+
compile-bytecode = true
|
|
170
|
+
managed = true
|
|
171
|
+
|
|
172
|
+
[tool.uv.pip]
|
|
173
|
+
compile-bytecode = true
|
|
174
|
+
require-hashes = true
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Statically-typed sentinel objects with singleton qualities.
|
|
2
|
+
|
|
3
|
+
`Sentinel` instances provide unique placeholder objects that maintain singleton behavior for a given type hint. They
|
|
4
|
+
are particularly useful as default parameter values when `None` is not appropriate or when type safety is desired.
|
|
5
|
+
|
|
6
|
+
The `Sentinel` class is particularly well-suited for use with types requiring parameters which are only available at
|
|
7
|
+
runtime, where creating a default instance of the type may not be possible in advance, but the structural contract
|
|
8
|
+
of the type is otherwise guaranteed to be fulfilled once present.
|
|
9
|
+
|
|
10
|
+
Key Features
|
|
11
|
+
-------------
|
|
12
|
+
- **Versatile:** Emulate any type, including user-defined types and types requiring parameters.
|
|
13
|
+
- **Type-safe:** Appears to the type-checker as an *instance* of the target type.
|
|
14
|
+
- **Thread-safe:** Safe for concurrent access across multiple threads.
|
|
15
|
+
- **Singleton behavior:** Only one instance exists per type hint.
|
|
16
|
+
- **Serializable:** Maintains singleton property across pickle operations.
|
|
17
|
+
- **Lightweight:** Sentinels are incredibly lightweight objects.
|
|
18
|
+
- **Immutable:** Cannot be modified after creation.
|
|
19
|
+
- **Falsy:** Always evaluates to `False` in boolean contexts.
|
|
20
|
+
- **Callable:** Calling a `Sentinel` instance always returns the instance.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
# Core
|
|
24
|
+
from ._core import Sentinel as Sentinel
|
|
25
|
+
from ._core import is_sentinel as is_sentinel
|
|
26
|
+
|
|
27
|
+
# Exceptions
|
|
28
|
+
from ._exceptions import InvalidHintError as InvalidHintError
|
|
29
|
+
from ._exceptions import SentinelError as SentinelError
|
|
30
|
+
from ._exceptions import SubscriptedTypeError as SubscriptedTypeError
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
from collections.abc import Callable
|
|
2
|
+
from threading import Lock
|
|
3
|
+
from typing import Any, ClassVar, NoReturn, SupportsIndex, TypeGuard, TypeVar, cast, final
|
|
4
|
+
from weakref import WeakValueDictionary
|
|
5
|
+
|
|
6
|
+
from ._exceptions import InvalidHintError, SubscriptedTypeError
|
|
7
|
+
|
|
8
|
+
type _InstanceCache = WeakValueDictionary[tuple[str, Any], 'Sentinel[Any]']
|
|
9
|
+
|
|
10
|
+
_OBJECT = object()
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@final
|
|
14
|
+
class Sentinel[T: Any]:
|
|
15
|
+
"""Statically-typed sentinel objects with singleton qualities.
|
|
16
|
+
|
|
17
|
+
`Sentinel` instances provide unique placeholder objects that maintain singleton behavior for a given type hint. They
|
|
18
|
+
are particularly useful as default parameter values when `None` is not appropriate or when type safety is desired.
|
|
19
|
+
|
|
20
|
+
The `Sentinel` class is particularly well-suited for use with types requiring parameters which are only available at
|
|
21
|
+
runtime, where creating a default instance of the type may not be possible in advance, but the structural contract
|
|
22
|
+
of the type is otherwise guaranteed to be fulfilled once present.
|
|
23
|
+
|
|
24
|
+
**Key features:**
|
|
25
|
+
|
|
26
|
+
- **Versatile:** Emulate any type, including user-defined types and types requiring parameters.
|
|
27
|
+
- **Type-safe:** Appears to the type-checker as an *instance* of the target type.
|
|
28
|
+
- **Thread-safe:** Safe for concurrent access across multiple threads.
|
|
29
|
+
- **Singleton behavior:** Only one instance exists per type hint.
|
|
30
|
+
- **Serializable:** Maintains singleton property across pickle operations.
|
|
31
|
+
- **Lightweight:** Sentinels are incredibly lightweight objects.
|
|
32
|
+
- **Immutable:** Cannot be modified after creation.
|
|
33
|
+
- **Falsy:** Always evaluates to `False` in boolean contexts.
|
|
34
|
+
- **Callable:** Calling a `Sentinel` instance always returns the instance.
|
|
35
|
+
|
|
36
|
+
Examples
|
|
37
|
+
--------
|
|
38
|
+
**Basic usage:**
|
|
39
|
+
|
|
40
|
+
>>> UNSET: str = Sentinel(str)
|
|
41
|
+
>>> def process(value: str = UNSET) -> str:
|
|
42
|
+
... if not value: # Sentinels are always falsy
|
|
43
|
+
... return 'No value'
|
|
44
|
+
... return f'Got: {value}'
|
|
45
|
+
|
|
46
|
+
**Type subscription syntax:**
|
|
47
|
+
|
|
48
|
+
>>> UNSET = Sentinel[str]()
|
|
49
|
+
>>> OTHER = Sentinel[str]()
|
|
50
|
+
>>> UNSET is OTHER # True - Singleton behavior
|
|
51
|
+
True
|
|
52
|
+
|
|
53
|
+
**With complex types:**
|
|
54
|
+
|
|
55
|
+
>>> CONFIG: dict[str, Any] = Sentinel(dict[str, Any])
|
|
56
|
+
>>> def setup(config: dict[str, Any] = CONFIG) -> None:
|
|
57
|
+
... if not config:
|
|
58
|
+
... config = {'default': True}
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
__slots__ = ('__weakref__', '_hint')
|
|
62
|
+
|
|
63
|
+
_cls_cache: ClassVar[_InstanceCache] = WeakValueDictionary()
|
|
64
|
+
_cls_hint: ClassVar[Any] = _OBJECT
|
|
65
|
+
_cls_lock: ClassVar[Lock] = Lock()
|
|
66
|
+
|
|
67
|
+
_hint: T
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def hint(self) -> T:
|
|
71
|
+
"""Return the type hint associated with this `Sentinel` instance.
|
|
72
|
+
|
|
73
|
+
Returns
|
|
74
|
+
-------
|
|
75
|
+
T
|
|
76
|
+
Type represented by the `Sentinel` instance.
|
|
77
|
+
"""
|
|
78
|
+
return self._hint
|
|
79
|
+
|
|
80
|
+
def __class_getitem__(cls, key: Any) -> T:
|
|
81
|
+
"""Support type subscription syntax like (e.g., `Sentinel[str]()`).
|
|
82
|
+
|
|
83
|
+
Parameters
|
|
84
|
+
----------
|
|
85
|
+
key : Any
|
|
86
|
+
Type to be used as the hint for the sentinel.
|
|
87
|
+
|
|
88
|
+
Returns
|
|
89
|
+
-------
|
|
90
|
+
T
|
|
91
|
+
Class object with the type hint stored for later instantiation, cast to the specified type.
|
|
92
|
+
"""
|
|
93
|
+
cls._cls_hint = key
|
|
94
|
+
if type(key) is TypeVar:
|
|
95
|
+
cls._cls_hint = Any
|
|
96
|
+
return cast('T', cls)
|
|
97
|
+
|
|
98
|
+
def __new__(cls, hint: Any = _OBJECT, /) -> Any:
|
|
99
|
+
"""Create or retrieve a `Sentinel` instance for the given `hint` type.
|
|
100
|
+
|
|
101
|
+
Implements the singleton pattern, ensuring that only one `Sentinel` instance exists for each unique
|
|
102
|
+
`(cls.__name__, hint)` combination. The method is thread-safe and lightweight; it attempts to return early with
|
|
103
|
+
any cached instance that might exist, doing so before acquiring the class-level lock.
|
|
104
|
+
|
|
105
|
+
Parameters
|
|
106
|
+
----------
|
|
107
|
+
hint : Any, optional
|
|
108
|
+
Type that this `Sentinel` should represent. If not provided, and if the class has not been otherwise
|
|
109
|
+
parameterized via subscription notation, defaults to `Any`.
|
|
110
|
+
|
|
111
|
+
Returns
|
|
112
|
+
-------
|
|
113
|
+
Sentinel[T]
|
|
114
|
+
`Sentinel` object instance for the given `hint` type, either created anew or retrievd from the class-level
|
|
115
|
+
`WeakValueDictionary` cache.
|
|
116
|
+
|
|
117
|
+
Raises
|
|
118
|
+
------
|
|
119
|
+
InvalidHintError
|
|
120
|
+
If `hint` is `None`, a `Sentinel` instance, or the `Sentinel` class object itself.
|
|
121
|
+
SubscriptedTypeError
|
|
122
|
+
If provided both a subscripted type parameter and a direct type argument and the types should differ (e.g.,
|
|
123
|
+
`Sentinel[A](B)` will raise a `SubscriptedTypeErorr`).
|
|
124
|
+
"""
|
|
125
|
+
if (_cls_hint := cls._cls_hint) is not _OBJECT:
|
|
126
|
+
cls._cls_hint = _OBJECT
|
|
127
|
+
if (hint is _OBJECT) and (_cls_hint is not _OBJECT):
|
|
128
|
+
hint = _cls_hint
|
|
129
|
+
if hint is _OBJECT:
|
|
130
|
+
hint = Any
|
|
131
|
+
|
|
132
|
+
key = (cls.__name__, hint)
|
|
133
|
+
if (inst := cls._cls_cache.get(key)) is not None:
|
|
134
|
+
return cast('T', inst)
|
|
135
|
+
|
|
136
|
+
if (hint is not _OBJECT) and (_cls_hint is not _OBJECT):
|
|
137
|
+
if (hint is not Any) and (_cls_hint is not Any):
|
|
138
|
+
if (hint != _cls_hint) and (hint is not _cls_hint):
|
|
139
|
+
raise SubscriptedTypeError(hint=hint, subscripted=_cls_hint)
|
|
140
|
+
|
|
141
|
+
if isinstance(hint, Sentinel) or (hint is Sentinel) or (hint is None):
|
|
142
|
+
raise InvalidHintError(hint)
|
|
143
|
+
|
|
144
|
+
with cls._cls_lock:
|
|
145
|
+
if (inst := cls._cls_cache.get(key)) is None:
|
|
146
|
+
inst = super().__new__(cls)
|
|
147
|
+
super().__setattr__(inst, '_hint', hint)
|
|
148
|
+
cls._cls_cache[key] = inst
|
|
149
|
+
|
|
150
|
+
return cast('T', inst)
|
|
151
|
+
|
|
152
|
+
def __getitem__(self, key: Any) -> T:
|
|
153
|
+
return cast('T', self)
|
|
154
|
+
|
|
155
|
+
def __call__(self, *args: Any, **kwds: Any) -> T:
|
|
156
|
+
return cast('T', self)
|
|
157
|
+
|
|
158
|
+
def __str__(self) -> str:
|
|
159
|
+
hint_name = str(self._hint)
|
|
160
|
+
if hint_name.startswith("<class '") and hint_name.endswith("'>"):
|
|
161
|
+
hint_name = hint_name[8:-2]
|
|
162
|
+
return f'<Sentinel: {hint_name}>'
|
|
163
|
+
|
|
164
|
+
def __repr__(self) -> str:
|
|
165
|
+
return f'<Sentinel: {self._hint!r}>'
|
|
166
|
+
|
|
167
|
+
def __hash__(self) -> int:
|
|
168
|
+
return hash((self.__class__, self._hint))
|
|
169
|
+
|
|
170
|
+
def __bool__(self) -> bool:
|
|
171
|
+
"""Return `False` - Sentinels are always "falsy".
|
|
172
|
+
|
|
173
|
+
This allows for natural usage patterns like:
|
|
174
|
+
|
|
175
|
+
```pycon
|
|
176
|
+
>>> if not value: # Where `value` might be a `Sentinel` instance
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
Returns
|
|
180
|
+
-------
|
|
181
|
+
bool
|
|
182
|
+
Always `False`.
|
|
183
|
+
"""
|
|
184
|
+
return False
|
|
185
|
+
|
|
186
|
+
def __eq__(self, other: object) -> bool:
|
|
187
|
+
"""Check equality with another object.
|
|
188
|
+
|
|
189
|
+
Two `Sentinels` are equal if they have the same `__class__` and `hint` type.
|
|
190
|
+
|
|
191
|
+
Parameters
|
|
192
|
+
----------
|
|
193
|
+
other : object
|
|
194
|
+
Object with which to compare.
|
|
195
|
+
|
|
196
|
+
Returns
|
|
197
|
+
-------
|
|
198
|
+
bool
|
|
199
|
+
- `True` if `other` is an object of the same `__class__` and `hint`.
|
|
200
|
+
- `False` otherwise.
|
|
201
|
+
"""
|
|
202
|
+
if not isinstance(other, self.__class__):
|
|
203
|
+
return NotImplemented
|
|
204
|
+
return self.__class__ == other.__class__ and self._hint == other._hint
|
|
205
|
+
|
|
206
|
+
def __copy__(self) -> 'Sentinel[T]':
|
|
207
|
+
return self
|
|
208
|
+
|
|
209
|
+
def __deepcopy__(self, _: Any) -> 'Sentinel[T]':
|
|
210
|
+
return self
|
|
211
|
+
|
|
212
|
+
def __reduce__(self) -> tuple[Callable[..., 'Sentinel[T]'], tuple[T]]:
|
|
213
|
+
return (self.__class__, (self._hint,))
|
|
214
|
+
|
|
215
|
+
def __reduce_ex__(self, protocol: SupportsIndex) -> tuple[Callable[..., 'Sentinel[T]'], tuple[T]]:
|
|
216
|
+
return self.__reduce__()
|
|
217
|
+
|
|
218
|
+
def __setattr__(self, name: str, value: Any) -> NoReturn:
|
|
219
|
+
msg = f'Cannot modify attributes of {self!r}'
|
|
220
|
+
raise AttributeError(msg)
|
|
221
|
+
|
|
222
|
+
def __delattr__(self, name: str) -> NoReturn:
|
|
223
|
+
msg = f'Cannot delete attributes of {self!r}'
|
|
224
|
+
raise AttributeError(msg)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def is_sentinel[T](obj: Any, typ: T | None = None) -> TypeGuard[Sentinel[T]]:
|
|
228
|
+
"""Return `True` if `obj` is a `Sentinel` instance, optionally further narrowed to be of type `typ`.
|
|
229
|
+
|
|
230
|
+
Parameters
|
|
231
|
+
----------
|
|
232
|
+
obj : Any
|
|
233
|
+
Possible `Sentinel` object instance.
|
|
234
|
+
typ : T | None, optional
|
|
235
|
+
Optional type to be used to further narrow the type of the `Sentinel` object instance.
|
|
236
|
+
If provided, and if `obj` is a `Sentinel` object instance, this must match `obj.hint`.
|
|
237
|
+
|
|
238
|
+
Returns
|
|
239
|
+
-------
|
|
240
|
+
TypeGuard[Sentinel[T]]
|
|
241
|
+
- `True` if `obj` is a `Sentinel` instance.
|
|
242
|
+
- `False` otherwise.
|
|
243
|
+
"""
|
|
244
|
+
if typ is not None:
|
|
245
|
+
return isinstance(obj, Sentinel) and obj.hint == typ
|
|
246
|
+
return isinstance(obj, Sentinel)
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class SentinelError(TypeError):
|
|
5
|
+
"""Base class from which all `typed-sentinels` `Exception` class objects inherit."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class InvalidHintError(SentinelError):
|
|
9
|
+
"""Argument for `hint` cannot be a `Sentinel` instance, the `Sentinel` class itself, or `None`."""
|
|
10
|
+
|
|
11
|
+
def __init__(self, hint: Any, /) -> None:
|
|
12
|
+
"""Initialize `InvalidHintError`.
|
|
13
|
+
|
|
14
|
+
Parameters
|
|
15
|
+
----------
|
|
16
|
+
hint : Any
|
|
17
|
+
The invalid argument for `hint` as provided to the `Sentinel` class constructor.
|
|
18
|
+
"""
|
|
19
|
+
msg = 'Argument for `hint` cannot be `None`\n'
|
|
20
|
+
if hint is not None:
|
|
21
|
+
msg = 'Argument for `hint` cannot be a `Sentinel` instance or `Sentinel` itself\n'
|
|
22
|
+
msg += f"Received argument for hint: '{hint!r}'"
|
|
23
|
+
super().__init__(msg)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class SubscriptedTypeError(SentinelError):
|
|
27
|
+
"""Subscripted type and explicit argument for `hint` must match."""
|
|
28
|
+
|
|
29
|
+
def __init__(self, hint: Any, subscripted: Any) -> None:
|
|
30
|
+
"""Initialize with the mismatched types.
|
|
31
|
+
|
|
32
|
+
Parameters
|
|
33
|
+
----------
|
|
34
|
+
hint : Any
|
|
35
|
+
Provided argument for `hint`.
|
|
36
|
+
subscripted : Any
|
|
37
|
+
Type provided via subscription notation to the `Sentinel` class object.
|
|
38
|
+
"""
|
|
39
|
+
msg = "Subscripted type and explicit argument for 'hint' must match\n"
|
|
40
|
+
msg += f' Subscripted type: {subscripted!r}\n'
|
|
41
|
+
msg += f' Hint: {hint!r}'
|
|
42
|
+
super().__init__(msg)
|
|
File without changes
|