smartswitchcase 2.0.0__py3-none-any.whl
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.
- smartswitchcase/__init__.py +36 -0
- smartswitchcase/_legacy.py +86 -0
- smartswitchcase/_patterns.py +246 -0
- smartswitchcase/_switch.py +164 -0
- smartswitchcase/py.typed +0 -0
- smartswitchcase-2.0.0.dist-info/METADATA +182 -0
- smartswitchcase-2.0.0.dist-info/RECORD +10 -0
- smartswitchcase-2.0.0.dist-info/WHEEL +5 -0
- smartswitchcase-2.0.0.dist-info/licenses/LICENSE +21 -0
- smartswitchcase-2.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""SmartSwitchCase: readable switch / case for Python, with patterns, predicates and dispatch tables.
|
|
2
|
+
|
|
3
|
+
from smartswitchcase import switch, between, regex
|
|
4
|
+
|
|
5
|
+
label = (switch(code)
|
|
6
|
+
.case(200, "ok")
|
|
7
|
+
.case(between(500, 599), "server error")
|
|
8
|
+
.case(regex(r"E\\d+"), lambda c: f"custom {c}")
|
|
9
|
+
.default("unknown"))
|
|
10
|
+
"""
|
|
11
|
+
from ._legacy import Case, SmartSwitchCase
|
|
12
|
+
from ._patterns import (
|
|
13
|
+
ANY,
|
|
14
|
+
Pattern,
|
|
15
|
+
all_of,
|
|
16
|
+
any_of,
|
|
17
|
+
between,
|
|
18
|
+
equals,
|
|
19
|
+
instance_of,
|
|
20
|
+
matches,
|
|
21
|
+
not_,
|
|
22
|
+
one_of,
|
|
23
|
+
partial,
|
|
24
|
+
regex,
|
|
25
|
+
where,
|
|
26
|
+
)
|
|
27
|
+
from ._switch import NoMatch, Switch, SwitchTable, switch
|
|
28
|
+
|
|
29
|
+
__version__ = "2.0.0"
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"switch", "Switch", "SwitchTable", "NoMatch",
|
|
33
|
+
"Pattern", "ANY", "equals", "one_of", "between", "instance_of", "regex", "where", "partial",
|
|
34
|
+
"all_of", "any_of", "not_", "matches",
|
|
35
|
+
"SmartSwitchCase", "Case",
|
|
36
|
+
]
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""The 1.x API (``SmartSwitchCase`` + ``Case``), kept so existing code keeps working.
|
|
2
|
+
|
|
3
|
+
Behaviour kept from 1.x: cases are compared with ``==``, every matching case runs in order, and
|
|
4
|
+
``result()`` gives the result of the last one that ran (or of the default).
|
|
5
|
+
|
|
6
|
+
Fixed in 2.0:
|
|
7
|
+
- an invalid case or default raises ``ValueError`` instead of calling ``exit()`` and killing the program;
|
|
8
|
+
- falsy values (``0``, ``""``, ``False``, ``None``) are valid case values;
|
|
9
|
+
- ``result()`` returns the stored result instead of running the function a second time;
|
|
10
|
+
- ``exc()`` also returns that result.
|
|
11
|
+
|
|
12
|
+
New code should use :func:`smartswitchcase.switch`.
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import warnings
|
|
17
|
+
from typing import Any, Callable
|
|
18
|
+
|
|
19
|
+
__all__ = ["Case", "SmartSwitchCase"]
|
|
20
|
+
|
|
21
|
+
_UNSET: Any = object()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Case:
|
|
25
|
+
"""One case of the 1.x API: a value and the function to call when it matches."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, value: Any = _UNSET, func: Callable[[], Any] | None = None) -> None:
|
|
28
|
+
self.value = value
|
|
29
|
+
self.func = func
|
|
30
|
+
|
|
31
|
+
def __repr__(self) -> str:
|
|
32
|
+
return f"Case({self.value!r}, {getattr(self.func, '__name__', self.func)!r})"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class SmartSwitchCase:
|
|
36
|
+
"""1.x switch. Prefer ``switch(subject).case(...).default(...)`` in new code."""
|
|
37
|
+
|
|
38
|
+
def __init__(self, obj: Any) -> None:
|
|
39
|
+
warnings.warn("SmartSwitchCase is the 1.x API; use smartswitchcase.switch() in new code",
|
|
40
|
+
DeprecationWarning, stacklevel=2)
|
|
41
|
+
self.__obj__ = obj
|
|
42
|
+
self.__cases__: list[Case] = []
|
|
43
|
+
self.__dft__: Callable[[], Any] | None = None
|
|
44
|
+
self.__isExec__ = False
|
|
45
|
+
self.__result__: Any = None
|
|
46
|
+
|
|
47
|
+
def case(self, case: Case) -> SmartSwitchCase:
|
|
48
|
+
if not isinstance(case, Case) or case.value is _UNSET:
|
|
49
|
+
raise ValueError("case() needs a Case(value, func)")
|
|
50
|
+
if not callable(case.func):
|
|
51
|
+
raise ValueError(f"the func of {case!r} must be callable")
|
|
52
|
+
self.__cases__.append(case)
|
|
53
|
+
return self
|
|
54
|
+
|
|
55
|
+
def default(self, func: Callable[[], Any] | None = None) -> SmartSwitchCase:
|
|
56
|
+
if not callable(func):
|
|
57
|
+
raise ValueError("default() needs a callable")
|
|
58
|
+
self.__dft__ = func
|
|
59
|
+
return self
|
|
60
|
+
|
|
61
|
+
def exc(self) -> Any:
|
|
62
|
+
"""Run every matching case (or the default) once, and return the last result."""
|
|
63
|
+
self.__isExec__ = True
|
|
64
|
+
ran = False
|
|
65
|
+
for case in self.__cases__:
|
|
66
|
+
if _equal(self.__obj__, case.value):
|
|
67
|
+
self.__result__ = case.func() # type: ignore[misc]
|
|
68
|
+
ran = True
|
|
69
|
+
if not ran:
|
|
70
|
+
self.__result__ = self.__dft__() if self.__dft__ else None
|
|
71
|
+
return self.__result__
|
|
72
|
+
|
|
73
|
+
exec = exc
|
|
74
|
+
|
|
75
|
+
def result(self) -> Any:
|
|
76
|
+
if not self.__isExec__:
|
|
77
|
+
warnings.warn("Please run exc() first to get the match result", stacklevel=2)
|
|
78
|
+
return None
|
|
79
|
+
return self.__result__
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _equal(a: Any, b: Any) -> bool:
|
|
83
|
+
try:
|
|
84
|
+
return bool(a == b)
|
|
85
|
+
except Exception: # noqa: BLE001
|
|
86
|
+
return False
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""Patterns: how a case decides whether it matches the subject.
|
|
2
|
+
|
|
3
|
+
A pattern can be a plain value (compared with ``==``) or one of the helpers below. Some objects
|
|
4
|
+
are interpreted automatically, see :func:`matches`.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import re
|
|
9
|
+
from collections.abc import Iterable, Mapping
|
|
10
|
+
from typing import Any, Callable
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"Pattern", "ANY", "equals", "one_of", "between", "instance_of", "regex", "where", "partial",
|
|
14
|
+
"all_of", "any_of", "not_", "matches",
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Pattern:
|
|
19
|
+
"""Base class of explicit patterns. Subclasses implement :meth:`test`."""
|
|
20
|
+
|
|
21
|
+
def test(self, subject: Any) -> bool: # pragma: no cover - abstract
|
|
22
|
+
raise NotImplementedError
|
|
23
|
+
|
|
24
|
+
def __or__(self, other: Any) -> Pattern:
|
|
25
|
+
return any_of(self, other)
|
|
26
|
+
|
|
27
|
+
def __and__(self, other: Any) -> Pattern:
|
|
28
|
+
return all_of(self, other)
|
|
29
|
+
|
|
30
|
+
def __invert__(self) -> Pattern:
|
|
31
|
+
return not_(self)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class _Any(Pattern):
|
|
35
|
+
def test(self, subject: Any) -> bool:
|
|
36
|
+
return True
|
|
37
|
+
|
|
38
|
+
def __repr__(self) -> str:
|
|
39
|
+
return "ANY"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
ANY: Pattern = _Any()
|
|
43
|
+
"""Matches everything. Useful as a wildcard inside :func:`partial`."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class equals(Pattern):
|
|
47
|
+
"""Plain equality, even for objects that would otherwise be interpreted (types, callables, sets)."""
|
|
48
|
+
|
|
49
|
+
def __init__(self, value: Any) -> None:
|
|
50
|
+
self.value = value
|
|
51
|
+
|
|
52
|
+
def test(self, subject: Any) -> bool:
|
|
53
|
+
return bool(subject == self.value)
|
|
54
|
+
|
|
55
|
+
def __repr__(self) -> str:
|
|
56
|
+
return f"equals({self.value!r})"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class one_of(Pattern):
|
|
60
|
+
"""Matches when the subject equals any of the values: ``one_of("y", "yes")``."""
|
|
61
|
+
|
|
62
|
+
def __init__(self, *values: Any) -> None:
|
|
63
|
+
if not values:
|
|
64
|
+
raise ValueError("one_of() needs at least one value")
|
|
65
|
+
self.values = values
|
|
66
|
+
|
|
67
|
+
def test(self, subject: Any) -> bool:
|
|
68
|
+
return any(subject == v for v in self.values)
|
|
69
|
+
|
|
70
|
+
def __repr__(self) -> str:
|
|
71
|
+
return f"one_of({', '.join(map(repr, self.values))})"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class between(Pattern):
|
|
75
|
+
"""``low <= subject <= high`` (both bounds included by default)."""
|
|
76
|
+
|
|
77
|
+
def __init__(self, low: Any, high: Any, *, inclusive: bool = True) -> None:
|
|
78
|
+
self.low, self.high, self.inclusive = low, high, inclusive
|
|
79
|
+
|
|
80
|
+
def test(self, subject: Any) -> bool:
|
|
81
|
+
try:
|
|
82
|
+
if self.inclusive:
|
|
83
|
+
return bool(self.low <= subject <= self.high)
|
|
84
|
+
return bool(self.low < subject < self.high)
|
|
85
|
+
except TypeError:
|
|
86
|
+
return False
|
|
87
|
+
|
|
88
|
+
def __repr__(self) -> str:
|
|
89
|
+
return f"between({self.low!r}, {self.high!r}{'' if self.inclusive else ', inclusive=False'})"
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class instance_of(Pattern):
|
|
93
|
+
"""``isinstance(subject, types)``. ``bool`` is not treated as an ``int`` unless asked for."""
|
|
94
|
+
|
|
95
|
+
def __init__(self, *types: type) -> None:
|
|
96
|
+
if not types or not all(isinstance(t, type) for t in types):
|
|
97
|
+
raise TypeError("instance_of() needs one or more types")
|
|
98
|
+
self.types = types
|
|
99
|
+
|
|
100
|
+
def test(self, subject: Any) -> bool:
|
|
101
|
+
if isinstance(subject, bool) and bool not in self.types and not any(t is object for t in self.types):
|
|
102
|
+
return False
|
|
103
|
+
return isinstance(subject, self.types)
|
|
104
|
+
|
|
105
|
+
def __repr__(self) -> str:
|
|
106
|
+
return f"instance_of({', '.join(t.__name__ for t in self.types)})"
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class regex(Pattern):
|
|
110
|
+
"""The whole string must match (``re.fullmatch``). The match object is available as ``ctx.match``."""
|
|
111
|
+
|
|
112
|
+
def __init__(self, pattern: str | re.Pattern[str], flags: int = 0) -> None:
|
|
113
|
+
self.pattern = re.compile(pattern, flags) if isinstance(pattern, str) else pattern
|
|
114
|
+
|
|
115
|
+
def test(self, subject: Any) -> bool:
|
|
116
|
+
return isinstance(subject, str) and self.pattern.fullmatch(subject) is not None
|
|
117
|
+
|
|
118
|
+
def __repr__(self) -> str:
|
|
119
|
+
return f"regex({self.pattern.pattern!r})"
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class where(Pattern):
|
|
123
|
+
"""A predicate: ``where(lambda v: v > 100)``. Exceptions raised by the predicate count as no match."""
|
|
124
|
+
|
|
125
|
+
def __init__(self, predicate: Callable[[Any], Any]) -> None:
|
|
126
|
+
if not callable(predicate):
|
|
127
|
+
raise TypeError("where() needs a callable")
|
|
128
|
+
self.predicate = predicate
|
|
129
|
+
|
|
130
|
+
def test(self, subject: Any) -> bool:
|
|
131
|
+
try:
|
|
132
|
+
return bool(self.predicate(subject))
|
|
133
|
+
except Exception: # noqa: BLE001 - a failing predicate simply does not match
|
|
134
|
+
return False
|
|
135
|
+
|
|
136
|
+
def __repr__(self) -> str:
|
|
137
|
+
return f"where({getattr(self.predicate, '__name__', 'predicate')})"
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class partial(Pattern):
|
|
141
|
+
"""Matches a mapping that contains at least these keys, each matching its own pattern (recursively).
|
|
142
|
+
|
|
143
|
+
``partial({"type": "user", "age": between(18, 99)})`` matches ``{"type": "user", "age": 30, "id": 7}``.
|
|
144
|
+
"""
|
|
145
|
+
|
|
146
|
+
def __init__(self, shape: Mapping[Any, Any]) -> None:
|
|
147
|
+
if not isinstance(shape, Mapping):
|
|
148
|
+
raise TypeError("partial() needs a mapping")
|
|
149
|
+
self.shape = shape
|
|
150
|
+
|
|
151
|
+
def test(self, subject: Any) -> bool:
|
|
152
|
+
if not isinstance(subject, Mapping):
|
|
153
|
+
return False
|
|
154
|
+
for key, pattern in self.shape.items():
|
|
155
|
+
if key not in subject:
|
|
156
|
+
return False
|
|
157
|
+
value = subject[key]
|
|
158
|
+
if isinstance(pattern, Mapping) and not isinstance(pattern, Pattern):
|
|
159
|
+
if not partial(pattern).test(value):
|
|
160
|
+
return False
|
|
161
|
+
elif not matches(pattern, value):
|
|
162
|
+
return False
|
|
163
|
+
return True
|
|
164
|
+
|
|
165
|
+
def __repr__(self) -> str:
|
|
166
|
+
return f"partial({dict(self.shape)!r})"
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
class all_of(Pattern):
|
|
170
|
+
"""Every pattern must match. Also written ``p1 & p2``."""
|
|
171
|
+
|
|
172
|
+
def __init__(self, *patterns: Any) -> None:
|
|
173
|
+
self.patterns = patterns
|
|
174
|
+
|
|
175
|
+
def test(self, subject: Any) -> bool:
|
|
176
|
+
return all(matches(p, subject) for p in self.patterns)
|
|
177
|
+
|
|
178
|
+
def __repr__(self) -> str:
|
|
179
|
+
return " & ".join(map(repr, self.patterns))
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
class any_of(Pattern):
|
|
183
|
+
"""At least one pattern must match. Also written ``p1 | p2``."""
|
|
184
|
+
|
|
185
|
+
def __init__(self, *patterns: Any) -> None:
|
|
186
|
+
self.patterns = patterns
|
|
187
|
+
|
|
188
|
+
def test(self, subject: Any) -> bool:
|
|
189
|
+
return any(matches(p, subject) for p in self.patterns)
|
|
190
|
+
|
|
191
|
+
def __repr__(self) -> str:
|
|
192
|
+
return " | ".join(map(repr, self.patterns))
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
class not_(Pattern):
|
|
196
|
+
"""The pattern must not match. Also written ``~p``."""
|
|
197
|
+
|
|
198
|
+
def __init__(self, pattern: Any) -> None:
|
|
199
|
+
self.pattern = pattern
|
|
200
|
+
|
|
201
|
+
def test(self, subject: Any) -> bool:
|
|
202
|
+
return not matches(self.pattern, subject)
|
|
203
|
+
|
|
204
|
+
def __repr__(self) -> str:
|
|
205
|
+
return f"~{self.pattern!r}"
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
_COLLECTIONS = (range, set, frozenset)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def matches(pattern: Any, subject: Any) -> bool:
|
|
212
|
+
"""Does ``subject`` match ``pattern``?
|
|
213
|
+
|
|
214
|
+
- a :class:`Pattern` (``between``, ``regex``, ``partial``…) decides by itself;
|
|
215
|
+
- a type matches its instances (``int``, ``MyClass``), or itself;
|
|
216
|
+
- a compiled regular expression must match the whole string;
|
|
217
|
+
- a ``range``, ``set`` or ``frozenset`` matches its members (a set subject is compared with ``==``);
|
|
218
|
+
- any other callable is a predicate (wrap it in :class:`equals` to compare functions);
|
|
219
|
+
- everything else is compared with ``==``, lists and dicts included.
|
|
220
|
+
"""
|
|
221
|
+
if isinstance(pattern, Pattern):
|
|
222
|
+
return pattern.test(subject)
|
|
223
|
+
if isinstance(pattern, type):
|
|
224
|
+
return subject is pattern or instance_of(pattern).test(subject)
|
|
225
|
+
if isinstance(pattern, re.Pattern):
|
|
226
|
+
return regex(pattern).test(subject)
|
|
227
|
+
if isinstance(pattern, _COLLECTIONS):
|
|
228
|
+
if isinstance(subject, _COLLECTIONS) or not _hashable_or_range(pattern, subject):
|
|
229
|
+
return bool(subject == pattern)
|
|
230
|
+
return subject in pattern
|
|
231
|
+
if callable(pattern):
|
|
232
|
+
return where(pattern).test(subject)
|
|
233
|
+
try:
|
|
234
|
+
return bool(subject == pattern)
|
|
235
|
+
except Exception: # noqa: BLE001 - e.g. numpy arrays: an ambiguous comparison is not a match
|
|
236
|
+
return False
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _hashable_or_range(pattern: Iterable[Any], subject: Any) -> bool:
|
|
240
|
+
if isinstance(pattern, range):
|
|
241
|
+
return isinstance(subject, int) and not isinstance(subject, bool)
|
|
242
|
+
try:
|
|
243
|
+
hash(subject)
|
|
244
|
+
return True
|
|
245
|
+
except TypeError:
|
|
246
|
+
return False
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""switch / SwitchTable: the modern API."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import inspect
|
|
5
|
+
from typing import Any, Callable, Generic, TypeVar
|
|
6
|
+
|
|
7
|
+
from ._patterns import matches
|
|
8
|
+
|
|
9
|
+
__all__ = ["switch", "Switch", "SwitchTable", "NoMatch"]
|
|
10
|
+
|
|
11
|
+
R = TypeVar("R")
|
|
12
|
+
_MISSING: Any = object()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class NoMatch(LookupError):
|
|
16
|
+
"""Raised by :meth:`Switch.run` (and strict tables) when no case matches and there is no default."""
|
|
17
|
+
|
|
18
|
+
def __init__(self, subject: Any) -> None:
|
|
19
|
+
super().__init__(f"no case matches {subject!r}")
|
|
20
|
+
self.subject = subject
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _call(result: Any, subject: Any) -> Any:
|
|
24
|
+
"""A result is either a value or a callable; callables get the subject when they accept an argument."""
|
|
25
|
+
if not callable(result) or isinstance(result, type):
|
|
26
|
+
return result
|
|
27
|
+
try:
|
|
28
|
+
params = inspect.signature(result).parameters.values()
|
|
29
|
+
except (TypeError, ValueError): # some builtins have no signature: try with the subject
|
|
30
|
+
return result(subject)
|
|
31
|
+
takes_arg = any(p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD, p.VAR_POSITIONAL) for p in params)
|
|
32
|
+
return result(subject) if takes_arg else result()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class SwitchTable(Generic[R]):
|
|
36
|
+
"""A reusable list of cases, evaluated against any subject: ``table(subject)``.
|
|
37
|
+
|
|
38
|
+
>>> size = SwitchTable().case(0, "empty").case(range(1, 10), "small").default("big")
|
|
39
|
+
>>> size(3), size(42)
|
|
40
|
+
('small', 'big')
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __init__(self, *, strict: bool = False) -> None:
|
|
44
|
+
self._cases: list[tuple[Any, Any]] = []
|
|
45
|
+
self._default: Any = _MISSING
|
|
46
|
+
self.strict = strict
|
|
47
|
+
|
|
48
|
+
def case(self, pattern: Any, result: Any = _MISSING) -> Any:
|
|
49
|
+
"""Add a case. Without ``result`` it works as a decorator: ``@table.case(1)``."""
|
|
50
|
+
if result is _MISSING:
|
|
51
|
+
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
|
|
52
|
+
self._cases.append((pattern, func))
|
|
53
|
+
return func
|
|
54
|
+
return decorator
|
|
55
|
+
self._cases.append((pattern, result))
|
|
56
|
+
return self
|
|
57
|
+
|
|
58
|
+
def cases(self, mapping: Any) -> SwitchTable[R]:
|
|
59
|
+
"""Add several ``{pattern: result}`` cases at once (patterns must be hashable)."""
|
|
60
|
+
for pattern, result in dict(mapping).items():
|
|
61
|
+
self._cases.append((pattern, result))
|
|
62
|
+
return self
|
|
63
|
+
|
|
64
|
+
def default(self, result: Any) -> SwitchTable[R]:
|
|
65
|
+
"""Result used when no case matches."""
|
|
66
|
+
self._default = result
|
|
67
|
+
return self
|
|
68
|
+
|
|
69
|
+
def match(self, subject: Any) -> tuple[int, Any] | None:
|
|
70
|
+
"""``(index, pattern)`` of the first matching case, or ``None``. Nothing is executed."""
|
|
71
|
+
for i, (pattern, _result) in enumerate(self._cases):
|
|
72
|
+
if matches(pattern, subject):
|
|
73
|
+
return i, pattern
|
|
74
|
+
return None
|
|
75
|
+
|
|
76
|
+
def __call__(self, subject: Any) -> Any:
|
|
77
|
+
found = self.match(subject)
|
|
78
|
+
if found is not None:
|
|
79
|
+
return _call(self._cases[found[0]][1], subject)
|
|
80
|
+
if self._default is not _MISSING:
|
|
81
|
+
return _call(self._default, subject)
|
|
82
|
+
if self.strict:
|
|
83
|
+
raise NoMatch(subject)
|
|
84
|
+
return None
|
|
85
|
+
|
|
86
|
+
def __len__(self) -> int:
|
|
87
|
+
return len(self._cases)
|
|
88
|
+
|
|
89
|
+
def __repr__(self) -> str:
|
|
90
|
+
return f"<SwitchTable {len(self._cases)} case(s){' + default' if self._default is not _MISSING else ''}>"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class Switch:
|
|
94
|
+
"""A switch bound to one subject. Build it with :func:`switch`.
|
|
95
|
+
|
|
96
|
+
Cases are checked in order; only the first match is executed, and only when the result is
|
|
97
|
+
asked for (``.default()``, ``.run()``, ``.get()``, ``.value``).
|
|
98
|
+
"""
|
|
99
|
+
|
|
100
|
+
def __init__(self, subject: Any) -> None:
|
|
101
|
+
self.subject = subject
|
|
102
|
+
self._table: SwitchTable[Any] = SwitchTable()
|
|
103
|
+
self._done = False
|
|
104
|
+
self._value: Any = None
|
|
105
|
+
|
|
106
|
+
def case(self, pattern: Any, result: Any = _MISSING) -> Any:
|
|
107
|
+
"""Add a case. ``result`` is a value or a callable (called with the subject if it takes one).
|
|
108
|
+
|
|
109
|
+
Without ``result`` it is a decorator: the decorated function becomes the result.
|
|
110
|
+
"""
|
|
111
|
+
if self._done:
|
|
112
|
+
raise RuntimeError("this switch has already been evaluated")
|
|
113
|
+
out = self._table.case(pattern, result)
|
|
114
|
+
return self if result is not _MISSING else out
|
|
115
|
+
|
|
116
|
+
def cases(self, mapping: Any) -> Switch:
|
|
117
|
+
self._table.cases(mapping)
|
|
118
|
+
return self
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def matched(self) -> bool:
|
|
122
|
+
"""Whether a case (not the default) matches. Nothing is executed."""
|
|
123
|
+
return self._table.match(self.subject) is not None
|
|
124
|
+
|
|
125
|
+
def default(self, result: Any) -> Any:
|
|
126
|
+
"""Evaluate: the result of the first matching case, else ``result``."""
|
|
127
|
+
self._table.default(result)
|
|
128
|
+
return self._evaluate()
|
|
129
|
+
|
|
130
|
+
def run(self) -> Any:
|
|
131
|
+
"""Evaluate: the result of the first matching case; :class:`NoMatch` if nothing matches."""
|
|
132
|
+
self._table.strict = True
|
|
133
|
+
return self._evaluate()
|
|
134
|
+
|
|
135
|
+
def get(self, default: Any = None) -> Any:
|
|
136
|
+
"""Evaluate: the result of the first matching case, else ``default`` (returned as is)."""
|
|
137
|
+
found = self._table.match(self.subject)
|
|
138
|
+
if found is None:
|
|
139
|
+
self._done, self._value = True, default
|
|
140
|
+
return default
|
|
141
|
+
return self._evaluate()
|
|
142
|
+
|
|
143
|
+
@property
|
|
144
|
+
def value(self) -> Any:
|
|
145
|
+
"""Same as :meth:`get` without a default, cached after the first evaluation."""
|
|
146
|
+
return self._value if self._done else self.get()
|
|
147
|
+
|
|
148
|
+
def _evaluate(self) -> Any:
|
|
149
|
+
if not self._done:
|
|
150
|
+
self._value = self._table(self.subject)
|
|
151
|
+
self._done = True
|
|
152
|
+
return self._value
|
|
153
|
+
|
|
154
|
+
def __repr__(self) -> str:
|
|
155
|
+
return f"<Switch {self.subject!r}: {len(self._table)} case(s)>"
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def switch(subject: Any) -> Switch:
|
|
159
|
+
"""Start a switch on ``subject``.
|
|
160
|
+
|
|
161
|
+
>>> switch(7).case(0, "zero").case(range(1, 10), "digit").default("other")
|
|
162
|
+
'digit'
|
|
163
|
+
"""
|
|
164
|
+
return Switch(subject)
|
smartswitchcase/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: smartswitchcase
|
|
3
|
+
Version: 2.0.0
|
|
4
|
+
Summary: Readable switch / case for Python: values, types, ranges, regex, predicates, dict shapes and reusable dispatch tables.
|
|
5
|
+
Author: Koffi Joel ONIPOH
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/koffijoel/SmartSwitchCase
|
|
8
|
+
Project-URL: Changelog, https://github.com/koffijoel/SmartSwitchCase/blob/main/CHANGELOG.md
|
|
9
|
+
Project-URL: Issues, https://github.com/koffijoel/SmartSwitchCase/issues
|
|
10
|
+
Project-URL: Funding, https://www.patreon.com/koffijoel
|
|
11
|
+
Keywords: switch,case,switch case,pattern matching,dispatch,predicate
|
|
12
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
17
|
+
Classifier: Typing :: Typed
|
|
18
|
+
Requires-Python: >=3.9
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
# SmartSwitchCase
|
|
24
|
+
|
|
25
|
+
[](https://pypi.org/project/smartswitchcase/)
|
|
26
|
+
[](https://pypi.org/project/smartswitchcase/)
|
|
27
|
+
[](https://github.com/koffijoel/SmartSwitchCase/actions)
|
|
28
|
+
[](LICENSE)
|
|
29
|
+
|
|
30
|
+
**Readable switch / case for Python, as an expression.** Match values, types, ranges, regular
|
|
31
|
+
expressions, predicates and the shape of dicts, then get a value back. Zero dependencies, fully
|
|
32
|
+
typed, Python 3.9+. [Français](README.fr.md)
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from smartswitchcase import switch, between, regex
|
|
36
|
+
|
|
37
|
+
label = (switch(status)
|
|
38
|
+
.case(200, "OK")
|
|
39
|
+
.case(between(500, 599), "Server error")
|
|
40
|
+
.case(regex(r"E\d+"), lambda code: f"Custom error {code}")
|
|
41
|
+
.default("Unknown"))
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Why, now that Python has `match`?
|
|
45
|
+
|
|
46
|
+
Python 3.10's `match` statement is great for destructuring. SmartSwitchCase covers what it does not:
|
|
47
|
+
|
|
48
|
+
- **It is an expression**: it returns a value, so it fits in a `return`, a lambda or a comprehension.
|
|
49
|
+
- **Cases are data**: build them at runtime, from config or a plugin registry, and reuse them as a
|
|
50
|
+
dispatch table.
|
|
51
|
+
- **Predicates, ranges and regexes are first-class**: `between(1, 9)`, `regex(r"E\d+")`,
|
|
52
|
+
`lambda v: v > 100`, combined with `&`, `|` and `~`.
|
|
53
|
+
- **Partial dict shapes**: route JSON payloads on the keys you care about with `partial({...})`.
|
|
54
|
+
- **It runs on Python 3.9.**
|
|
55
|
+
|
|
56
|
+
## Install
|
|
57
|
+
|
|
58
|
+
```sh
|
|
59
|
+
pip install smartswitchcase
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Usage
|
|
63
|
+
|
|
64
|
+
### A switch returns the result of the first matching case
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from smartswitchcase import switch
|
|
68
|
+
|
|
69
|
+
switch(7).case(0, "zero").case(range(1, 10), "digit").default("other") # 'digit'
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
- Cases are checked in order; **only the first match runs**, and nothing runs before the result is
|
|
73
|
+
asked for.
|
|
74
|
+
- A result is a value or a callable. A callable receives the subject if it takes an argument:
|
|
75
|
+
`.case(int, lambda n: n * 2)`, or nothing if it does not: `.case(0, lambda: "zero")`.
|
|
76
|
+
|
|
77
|
+
How to get the result:
|
|
78
|
+
|
|
79
|
+
| Call | When nothing matches |
|
|
80
|
+
|---|---|
|
|
81
|
+
| `.default(result)` | uses `result` (a value or a callable) |
|
|
82
|
+
| `.get(fallback=None)` | returns `fallback` |
|
|
83
|
+
| `.run()` | raises `NoMatch` |
|
|
84
|
+
| `.value` | `None`; the result is computed once, then cached |
|
|
85
|
+
| `.matched` | `False` (it only checks, runs nothing) |
|
|
86
|
+
|
|
87
|
+
### Patterns
|
|
88
|
+
|
|
89
|
+
| Pattern | Matches |
|
|
90
|
+
|---|---|
|
|
91
|
+
| `42`, `"text"`, `[1, 2]`, `{"a": 1}` | equal values (`==`) |
|
|
92
|
+
| `int`, `MyClass` | instances (`bool` is not treated as an `int`), or the type itself |
|
|
93
|
+
| `range(1, 10)`, `{"a", "b"}`, `frozenset(...)` | members |
|
|
94
|
+
| `re.compile(...)`, `regex(r"...")` | strings that fully match |
|
|
95
|
+
| `lambda v: ...`, `where(func)` | values for which the predicate is true (exceptions mean "no") |
|
|
96
|
+
| `one_of("y", "yes")` | any of the values |
|
|
97
|
+
| `between(lo, hi, inclusive=True)` | `lo <= v <= hi` |
|
|
98
|
+
| `instance_of(int, float)` | several types |
|
|
99
|
+
| `partial({"type": "user", "age": between(18, 99)})` | dicts containing these keys, each matching its pattern, recursively |
|
|
100
|
+
| `ANY` | everything (a wildcard inside `partial`) |
|
|
101
|
+
| `equals(x)` | `== x` even when `x` is a type, a set or a function |
|
|
102
|
+
| `p1 & p2`, `p1 \| p2`, `~p` (or `all_of`, `any_of`, `not_`) | combinations |
|
|
103
|
+
|
|
104
|
+
### Reusable dispatch tables
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
from smartswitchcase import SwitchTable, NoMatch
|
|
108
|
+
|
|
109
|
+
commands = SwitchTable(strict=True)
|
|
110
|
+
|
|
111
|
+
@commands.case("start")
|
|
112
|
+
def start():
|
|
113
|
+
return "starting"
|
|
114
|
+
|
|
115
|
+
@commands.case(lambda cmd: cmd.startswith("say "))
|
|
116
|
+
def say(cmd):
|
|
117
|
+
return cmd[4:]
|
|
118
|
+
|
|
119
|
+
commands("say hello") # 'hello'
|
|
120
|
+
commands("dance") # raises NoMatch (strict); without strict, returns None
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
`.cases({"a": 1, "b": 2})` adds several cases at once, and `.match(subject)` tells which case would
|
|
124
|
+
run without running it.
|
|
125
|
+
|
|
126
|
+
### Routing JSON payloads
|
|
127
|
+
|
|
128
|
+
```python
|
|
129
|
+
from smartswitchcase import switch, partial, between, ANY
|
|
130
|
+
|
|
131
|
+
(switch(event)
|
|
132
|
+
.case(partial({"type": "user.created", "user": {"age": between(18, 130)}}), create_adult)
|
|
133
|
+
.case(partial({"type": "order.paid", "order": {"id": ANY}}), ship)
|
|
134
|
+
.default(ignore))
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
More in [`examples/`](examples/).
|
|
138
|
+
|
|
139
|
+
## Migrating from 1.x
|
|
140
|
+
|
|
141
|
+
The 1.x API still works. It shows a `DeprecationWarning`, and its dangerous bugs are fixed:
|
|
142
|
+
|
|
143
|
+
| 1.x behaviour | 2.0 |
|
|
144
|
+
|---|---|
|
|
145
|
+
| A wrong `case()` or `default()` called `exit()` and **stopped your program** | raises `ValueError` |
|
|
146
|
+
| `0`, `""`, `False` and `None` could not be case values | they can |
|
|
147
|
+
| `result()` **ran the function a second time** | returns the stored result |
|
|
148
|
+
| `exc()` returned nothing | returns the result |
|
|
149
|
+
|
|
150
|
+
```python
|
|
151
|
+
# 1.x
|
|
152
|
+
swc = SmartSwitchCase(value)
|
|
153
|
+
swc.case(Case(1, lambda: "one"))
|
|
154
|
+
swc.case(Case(2, lambda: "two"))
|
|
155
|
+
swc.default(lambda: "other")
|
|
156
|
+
swc.exc()
|
|
157
|
+
result = swc.result()
|
|
158
|
+
|
|
159
|
+
# 2.0
|
|
160
|
+
result = switch(value).case(1, "one").case(2, "two").default("other")
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
One difference to know: 1.x ran **every** matching case, while `switch()` runs only the first one,
|
|
164
|
+
like a real switch.
|
|
165
|
+
|
|
166
|
+
## Development
|
|
167
|
+
|
|
168
|
+
```sh
|
|
169
|
+
python -m unittest discover -s tests # tests
|
|
170
|
+
ruff check . && mypy smartswitchcase # lint and types (strict)
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
To release, bump `__version__` in `smartswitchcase/__init__.py` and add a `CHANGELOG.md` section.
|
|
174
|
+
CI tags the version, publishes the GitHub release and the PyPI package.
|
|
175
|
+
|
|
176
|
+
## Support
|
|
177
|
+
|
|
178
|
+
If this library saves you time, you can support my work on [Patreon](https://www.patreon.com/koffijoel).
|
|
179
|
+
|
|
180
|
+
## License
|
|
181
|
+
|
|
182
|
+
[MIT](LICENSE), by [Koffi Joel](https://github.com/koffijoel).
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
smartswitchcase/__init__.py,sha256=ZZOCNwpMdBFz3qcEFJclOwhYGwfFNBcpReFz99PLsbo,1173
|
|
2
|
+
smartswitchcase/_legacy.py,sha256=4_3IyolY3H0hWzyyFMp_XFLHjY_BH90mliBur3bd0Sg,3033
|
|
3
|
+
smartswitchcase/_patterns.py,sha256=0aiIKt_iN16_ZwO2_-Qw_ceCMKnZe3mu6YcEKpuEbPU,8159
|
|
4
|
+
smartswitchcase/_switch.py,sha256=rnxLQfjuToR42-xkgGBJl1iFnfeLNFYPuVEROovpOEA,5893
|
|
5
|
+
smartswitchcase/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
smartswitchcase-2.0.0.dist-info/licenses/LICENSE,sha256=0ZxKROO-IWJvM4XdMk6nFeGT1_Guec5qkhtY-NtXZjM,1075
|
|
7
|
+
smartswitchcase-2.0.0.dist-info/METADATA,sha256=E0JWIVc07HEaXtSV0Ujsky2H35wbEoEhKLjaIQ7HP0Q,6574
|
|
8
|
+
smartswitchcase-2.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
smartswitchcase-2.0.0.dist-info/top_level.txt,sha256=ayeD2btz8pywYp9RHkEptYDs4hqn1DAek_kSmwu8DOw,16
|
|
10
|
+
smartswitchcase-2.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) [2020] [SmartSwitchCase]
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
smartswitchcase
|