smartswitchcase 1.0__tar.gz → 2.0.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.
@@ -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,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
+ [![PyPI](https://img.shields.io/pypi/v/smartswitchcase.svg)](https://pypi.org/project/smartswitchcase/)
26
+ [![Python](https://img.shields.io/pypi/pyversions/smartswitchcase.svg)](https://pypi.org/project/smartswitchcase/)
27
+ [![Tests](https://github.com/koffijoel/SmartSwitchCase/actions/workflows/release.yml/badge.svg)](https://github.com/koffijoel/SmartSwitchCase/actions)
28
+ [![License](https://img.shields.io/pypi/l/smartswitchcase.svg)](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,160 @@
1
+ # SmartSwitchCase
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/smartswitchcase.svg)](https://pypi.org/project/smartswitchcase/)
4
+ [![Python](https://img.shields.io/pypi/pyversions/smartswitchcase.svg)](https://pypi.org/project/smartswitchcase/)
5
+ [![Tests](https://github.com/koffijoel/SmartSwitchCase/actions/workflows/release.yml/badge.svg)](https://github.com/koffijoel/SmartSwitchCase/actions)
6
+ [![License](https://img.shields.io/pypi/l/smartswitchcase.svg)](LICENSE)
7
+
8
+ **Readable switch / case for Python, as an expression.** Match values, types, ranges, regular
9
+ expressions, predicates and the shape of dicts, then get a value back. Zero dependencies, fully
10
+ typed, Python 3.9+. [Français](README.fr.md)
11
+
12
+ ```python
13
+ from smartswitchcase import switch, between, regex
14
+
15
+ label = (switch(status)
16
+ .case(200, "OK")
17
+ .case(between(500, 599), "Server error")
18
+ .case(regex(r"E\d+"), lambda code: f"Custom error {code}")
19
+ .default("Unknown"))
20
+ ```
21
+
22
+ ## Why, now that Python has `match`?
23
+
24
+ Python 3.10's `match` statement is great for destructuring. SmartSwitchCase covers what it does not:
25
+
26
+ - **It is an expression**: it returns a value, so it fits in a `return`, a lambda or a comprehension.
27
+ - **Cases are data**: build them at runtime, from config or a plugin registry, and reuse them as a
28
+ dispatch table.
29
+ - **Predicates, ranges and regexes are first-class**: `between(1, 9)`, `regex(r"E\d+")`,
30
+ `lambda v: v > 100`, combined with `&`, `|` and `~`.
31
+ - **Partial dict shapes**: route JSON payloads on the keys you care about with `partial({...})`.
32
+ - **It runs on Python 3.9.**
33
+
34
+ ## Install
35
+
36
+ ```sh
37
+ pip install smartswitchcase
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ ### A switch returns the result of the first matching case
43
+
44
+ ```python
45
+ from smartswitchcase import switch
46
+
47
+ switch(7).case(0, "zero").case(range(1, 10), "digit").default("other") # 'digit'
48
+ ```
49
+
50
+ - Cases are checked in order; **only the first match runs**, and nothing runs before the result is
51
+ asked for.
52
+ - A result is a value or a callable. A callable receives the subject if it takes an argument:
53
+ `.case(int, lambda n: n * 2)`, or nothing if it does not: `.case(0, lambda: "zero")`.
54
+
55
+ How to get the result:
56
+
57
+ | Call | When nothing matches |
58
+ |---|---|
59
+ | `.default(result)` | uses `result` (a value or a callable) |
60
+ | `.get(fallback=None)` | returns `fallback` |
61
+ | `.run()` | raises `NoMatch` |
62
+ | `.value` | `None`; the result is computed once, then cached |
63
+ | `.matched` | `False` (it only checks, runs nothing) |
64
+
65
+ ### Patterns
66
+
67
+ | Pattern | Matches |
68
+ |---|---|
69
+ | `42`, `"text"`, `[1, 2]`, `{"a": 1}` | equal values (`==`) |
70
+ | `int`, `MyClass` | instances (`bool` is not treated as an `int`), or the type itself |
71
+ | `range(1, 10)`, `{"a", "b"}`, `frozenset(...)` | members |
72
+ | `re.compile(...)`, `regex(r"...")` | strings that fully match |
73
+ | `lambda v: ...`, `where(func)` | values for which the predicate is true (exceptions mean "no") |
74
+ | `one_of("y", "yes")` | any of the values |
75
+ | `between(lo, hi, inclusive=True)` | `lo <= v <= hi` |
76
+ | `instance_of(int, float)` | several types |
77
+ | `partial({"type": "user", "age": between(18, 99)})` | dicts containing these keys, each matching its pattern, recursively |
78
+ | `ANY` | everything (a wildcard inside `partial`) |
79
+ | `equals(x)` | `== x` even when `x` is a type, a set or a function |
80
+ | `p1 & p2`, `p1 \| p2`, `~p` (or `all_of`, `any_of`, `not_`) | combinations |
81
+
82
+ ### Reusable dispatch tables
83
+
84
+ ```python
85
+ from smartswitchcase import SwitchTable, NoMatch
86
+
87
+ commands = SwitchTable(strict=True)
88
+
89
+ @commands.case("start")
90
+ def start():
91
+ return "starting"
92
+
93
+ @commands.case(lambda cmd: cmd.startswith("say "))
94
+ def say(cmd):
95
+ return cmd[4:]
96
+
97
+ commands("say hello") # 'hello'
98
+ commands("dance") # raises NoMatch (strict); without strict, returns None
99
+ ```
100
+
101
+ `.cases({"a": 1, "b": 2})` adds several cases at once, and `.match(subject)` tells which case would
102
+ run without running it.
103
+
104
+ ### Routing JSON payloads
105
+
106
+ ```python
107
+ from smartswitchcase import switch, partial, between, ANY
108
+
109
+ (switch(event)
110
+ .case(partial({"type": "user.created", "user": {"age": between(18, 130)}}), create_adult)
111
+ .case(partial({"type": "order.paid", "order": {"id": ANY}}), ship)
112
+ .default(ignore))
113
+ ```
114
+
115
+ More in [`examples/`](examples/).
116
+
117
+ ## Migrating from 1.x
118
+
119
+ The 1.x API still works. It shows a `DeprecationWarning`, and its dangerous bugs are fixed:
120
+
121
+ | 1.x behaviour | 2.0 |
122
+ |---|---|
123
+ | A wrong `case()` or `default()` called `exit()` and **stopped your program** | raises `ValueError` |
124
+ | `0`, `""`, `False` and `None` could not be case values | they can |
125
+ | `result()` **ran the function a second time** | returns the stored result |
126
+ | `exc()` returned nothing | returns the result |
127
+
128
+ ```python
129
+ # 1.x
130
+ swc = SmartSwitchCase(value)
131
+ swc.case(Case(1, lambda: "one"))
132
+ swc.case(Case(2, lambda: "two"))
133
+ swc.default(lambda: "other")
134
+ swc.exc()
135
+ result = swc.result()
136
+
137
+ # 2.0
138
+ result = switch(value).case(1, "one").case(2, "two").default("other")
139
+ ```
140
+
141
+ One difference to know: 1.x ran **every** matching case, while `switch()` runs only the first one,
142
+ like a real switch.
143
+
144
+ ## Development
145
+
146
+ ```sh
147
+ python -m unittest discover -s tests # tests
148
+ ruff check . && mypy smartswitchcase # lint and types (strict)
149
+ ```
150
+
151
+ To release, bump `__version__` in `smartswitchcase/__init__.py` and add a `CHANGELOG.md` section.
152
+ CI tags the version, publishes the GitHub release and the PyPI package.
153
+
154
+ ## Support
155
+
156
+ If this library saves you time, you can support my work on [Patreon](https://www.patreon.com/koffijoel).
157
+
158
+ ## License
159
+
160
+ [MIT](LICENSE), by [Koffi Joel](https://github.com/koffijoel).
@@ -0,0 +1,47 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "smartswitchcase"
7
+ dynamic = ["version"]
8
+ description = "Readable switch / case for Python: values, types, ranges, regex, predicates, dict shapes and reusable dispatch tables."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "Koffi Joel ONIPOH" }]
13
+ requires-python = ">=3.9"
14
+ dependencies = []
15
+ keywords = ["switch", "case", "switch case", "pattern matching", "dispatch", "predicate"]
16
+ classifiers = [
17
+ "Development Status :: 5 - Production/Stable",
18
+ "Intended Audience :: Developers",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3 :: Only",
21
+ "Topic :: Software Development :: Libraries :: Python Modules",
22
+ "Typing :: Typed",
23
+ ]
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/koffijoel/SmartSwitchCase"
27
+ Changelog = "https://github.com/koffijoel/SmartSwitchCase/blob/main/CHANGELOG.md"
28
+ Issues = "https://github.com/koffijoel/SmartSwitchCase/issues"
29
+ Funding = "https://www.patreon.com/koffijoel"
30
+
31
+ [tool.setuptools]
32
+ packages = ["smartswitchcase"]
33
+
34
+ [tool.setuptools.package-data]
35
+ smartswitchcase = ["py.typed"]
36
+
37
+ [tool.setuptools.dynamic]
38
+ version = { attr = "smartswitchcase.__version__" }
39
+
40
+ [tool.ruff]
41
+ line-length = 120
42
+
43
+ [tool.ruff.lint]
44
+ select = ["E", "F", "W", "B", "UP", "I"]
45
+
46
+ [tool.mypy]
47
+ strict = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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