tagged-enum 1.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.
- tagged_enum-1.0.0/.gitignore +218 -0
- tagged_enum-1.0.0/LICENSE +21 -0
- tagged_enum-1.0.0/PKG-INFO +230 -0
- tagged_enum-1.0.0/README.md +205 -0
- tagged_enum-1.0.0/pyproject.toml +52 -0
- tagged_enum-1.0.0/src/tagged_enum/TaggedEnum.py +262 -0
- tagged_enum-1.0.0/src/tagged_enum/__init__.py +7 -0
- tagged_enum-1.0.0/src/tagged_enum/py.typed +0 -0
- tagged_enum-1.0.0/tests/helpers.py +11 -0
- tagged_enum-1.0.0/tests/test_construction.py +34 -0
- tagged_enum-1.0.0/tests/test_equality_and_hashing.py +62 -0
- tagged_enum-1.0.0/tests/test_generic_payloads.py +55 -0
- tagged_enum-1.0.0/tests/test_immutability.py +16 -0
- tagged_enum-1.0.0/tests/test_kind.py +14 -0
- tagged_enum-1.0.0/tests/test_make_and_payload_type.py +19 -0
- tagged_enum-1.0.0/tests/test_multiple_enums.py +37 -0
- tagged_enum-1.0.0/tests/test_pattern_matching.py +36 -0
- tagged_enum-1.0.0/tests/test_recursive_cases.py +30 -0
- tagged_enum-1.0.0/tests/test_repr.py +10 -0
- tagged_enum-1.0.0/tests/test_type_checking.py +19 -0
- tagged_enum-1.0.0/uv.lock +86 -0
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[codz]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
parts/
|
|
20
|
+
sdist/
|
|
21
|
+
var/
|
|
22
|
+
wheels/
|
|
23
|
+
share/python-wheels/
|
|
24
|
+
*.egg-info/
|
|
25
|
+
.installed.cfg
|
|
26
|
+
*.egg
|
|
27
|
+
MANIFEST
|
|
28
|
+
|
|
29
|
+
# PyInstaller
|
|
30
|
+
# Usually these files are written by a python script from a template
|
|
31
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
32
|
+
*.manifest
|
|
33
|
+
*.spec
|
|
34
|
+
|
|
35
|
+
# Installer logs
|
|
36
|
+
pip-log.txt
|
|
37
|
+
pip-delete-this-directory.txt
|
|
38
|
+
|
|
39
|
+
# Unit test / coverage reports
|
|
40
|
+
htmlcov/
|
|
41
|
+
.tox/
|
|
42
|
+
.nox/
|
|
43
|
+
.coverage
|
|
44
|
+
.coverage.*
|
|
45
|
+
.cache
|
|
46
|
+
nosetests.xml
|
|
47
|
+
coverage.xml
|
|
48
|
+
*.cover
|
|
49
|
+
*.py.cover
|
|
50
|
+
.hypothesis/
|
|
51
|
+
.pytest_cache/
|
|
52
|
+
cover/
|
|
53
|
+
|
|
54
|
+
# Translations
|
|
55
|
+
*.mo
|
|
56
|
+
*.pot
|
|
57
|
+
|
|
58
|
+
# Django stuff:
|
|
59
|
+
*.log
|
|
60
|
+
local_settings.py
|
|
61
|
+
db.sqlite3
|
|
62
|
+
db.sqlite3-journal
|
|
63
|
+
|
|
64
|
+
# Flask stuff:
|
|
65
|
+
instance/
|
|
66
|
+
.webassets-cache
|
|
67
|
+
|
|
68
|
+
# Scrapy stuff:
|
|
69
|
+
.scrapy
|
|
70
|
+
|
|
71
|
+
# Sphinx documentation
|
|
72
|
+
docs/_build/
|
|
73
|
+
|
|
74
|
+
# PyBuilder
|
|
75
|
+
.pybuilder/
|
|
76
|
+
target/
|
|
77
|
+
|
|
78
|
+
# Jupyter Notebook
|
|
79
|
+
.ipynb_checkpoints
|
|
80
|
+
|
|
81
|
+
# IPython
|
|
82
|
+
profile_default/
|
|
83
|
+
ipython_config.py
|
|
84
|
+
|
|
85
|
+
# pyenv
|
|
86
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
87
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
88
|
+
# .python-version
|
|
89
|
+
|
|
90
|
+
# pipenv
|
|
91
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
92
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
93
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
94
|
+
# install all needed dependencies.
|
|
95
|
+
# Pipfile.lock
|
|
96
|
+
|
|
97
|
+
# UV
|
|
98
|
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
|
99
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
100
|
+
# commonly ignored for libraries.
|
|
101
|
+
# uv.lock
|
|
102
|
+
|
|
103
|
+
# poetry
|
|
104
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
105
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
106
|
+
# commonly ignored for libraries.
|
|
107
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
108
|
+
# poetry.lock
|
|
109
|
+
# poetry.toml
|
|
110
|
+
|
|
111
|
+
# pdm
|
|
112
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
113
|
+
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
|
114
|
+
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
|
115
|
+
# pdm.lock
|
|
116
|
+
# pdm.toml
|
|
117
|
+
.pdm-python
|
|
118
|
+
.pdm-build/
|
|
119
|
+
|
|
120
|
+
# pixi
|
|
121
|
+
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
|
122
|
+
# pixi.lock
|
|
123
|
+
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
|
124
|
+
# in the .venv directory. It is recommended not to include this directory in version control.
|
|
125
|
+
.pixi
|
|
126
|
+
|
|
127
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
128
|
+
__pypackages__/
|
|
129
|
+
|
|
130
|
+
# Celery stuff
|
|
131
|
+
celerybeat-schedule
|
|
132
|
+
celerybeat.pid
|
|
133
|
+
|
|
134
|
+
# Redis
|
|
135
|
+
*.rdb
|
|
136
|
+
*.aof
|
|
137
|
+
*.pid
|
|
138
|
+
|
|
139
|
+
# RabbitMQ
|
|
140
|
+
mnesia/
|
|
141
|
+
rabbitmq/
|
|
142
|
+
rabbitmq-data/
|
|
143
|
+
|
|
144
|
+
# ActiveMQ
|
|
145
|
+
activemq-data/
|
|
146
|
+
|
|
147
|
+
# SageMath parsed files
|
|
148
|
+
*.sage.py
|
|
149
|
+
|
|
150
|
+
# Environments
|
|
151
|
+
.env
|
|
152
|
+
.envrc
|
|
153
|
+
.venv
|
|
154
|
+
env/
|
|
155
|
+
venv/
|
|
156
|
+
ENV/
|
|
157
|
+
env.bak/
|
|
158
|
+
venv.bak/
|
|
159
|
+
|
|
160
|
+
# Spyder project settings
|
|
161
|
+
.spyderproject
|
|
162
|
+
.spyproject
|
|
163
|
+
|
|
164
|
+
# Rope project settings
|
|
165
|
+
.ropeproject
|
|
166
|
+
|
|
167
|
+
# mkdocs documentation
|
|
168
|
+
/site
|
|
169
|
+
|
|
170
|
+
# mypy
|
|
171
|
+
.mypy_cache/
|
|
172
|
+
.dmypy.json
|
|
173
|
+
dmypy.json
|
|
174
|
+
|
|
175
|
+
# Pyre type checker
|
|
176
|
+
.pyre/
|
|
177
|
+
|
|
178
|
+
# pytype static type analyzer
|
|
179
|
+
.pytype/
|
|
180
|
+
|
|
181
|
+
# Cython debug symbols
|
|
182
|
+
cython_debug/
|
|
183
|
+
|
|
184
|
+
# PyCharm
|
|
185
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
186
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
187
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
188
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
189
|
+
# .idea/
|
|
190
|
+
|
|
191
|
+
# Abstra
|
|
192
|
+
# Abstra is an AI-powered process automation framework.
|
|
193
|
+
# Ignore directories containing user credentials, local state, and settings.
|
|
194
|
+
# Learn more at https://abstra.io/docs
|
|
195
|
+
.abstra/
|
|
196
|
+
|
|
197
|
+
# Visual Studio Code
|
|
198
|
+
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
|
199
|
+
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
|
200
|
+
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
|
201
|
+
# you could uncomment the following to ignore the entire vscode folder
|
|
202
|
+
# .vscode/
|
|
203
|
+
# Temporary file for partial code execution
|
|
204
|
+
tempCodeRunnerFile.py
|
|
205
|
+
|
|
206
|
+
# Ruff stuff:
|
|
207
|
+
.ruff_cache/
|
|
208
|
+
|
|
209
|
+
# PyPI configuration file
|
|
210
|
+
.pypirc
|
|
211
|
+
|
|
212
|
+
# Marimo
|
|
213
|
+
marimo/_static/
|
|
214
|
+
marimo/_lsp/
|
|
215
|
+
__marimo__/
|
|
216
|
+
|
|
217
|
+
# Streamlit
|
|
218
|
+
.streamlit/secrets.toml
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Robert Barker
|
|
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,230 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tagged-enum
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Tagged enums for Python
|
|
5
|
+
Project-URL: Homepage, https://github.com/rob-barker/tagged-enum
|
|
6
|
+
Project-URL: Repository, https://github.com/rob-barker/tagged-enum
|
|
7
|
+
Project-URL: Issues, https://github.com/rob-barker/tagged-enum/issues
|
|
8
|
+
Author-email: Rob Barker <rob.barker.official@gmail.com>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: discriminated-union,enum,pattern-matching,tagged-enum,tagged-union
|
|
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: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Provides-Extra: test
|
|
23
|
+
Requires-Dist: pytest>=7.0; extra == 'test'
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# tagged-enum
|
|
27
|
+
|
|
28
|
+
Tagged enums for Python ๐.
|
|
29
|
+
|
|
30
|
+
Tagged enums (a.k.a. discriminated unions, enums with associated values, etc.)
|
|
31
|
+
are enums where each case carries a typed **payload**.
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
from tagged_enum import TaggedEnum
|
|
35
|
+
|
|
36
|
+
# Declare a tagged enum
|
|
37
|
+
class Shape(TaggedEnum):
|
|
38
|
+
CIRCLE = float # radius
|
|
39
|
+
RECTANGLE = tuple[float, float] # width, height
|
|
40
|
+
TRIANGLE = tuple[float, float] # base, height
|
|
41
|
+
|
|
42
|
+
def area(shape: Shape) -> float:
|
|
43
|
+
# match over enum cases
|
|
44
|
+
match shape:
|
|
45
|
+
case Shape(kind=Shape.CIRCLE, payload=radius):
|
|
46
|
+
return 3.14159 * radius ** 2
|
|
47
|
+
case Shape(kind=Shape.RECTANGLE, payload=(w, h)):
|
|
48
|
+
return w * h
|
|
49
|
+
case Shape(kind=Shape.TRIANGLE, payload=(b, h)):
|
|
50
|
+
return 0.5 * b * h
|
|
51
|
+
|
|
52
|
+
shapes = [Shape.CIRCLE(2.0),
|
|
53
|
+
Shape.RECTANGLE((3.0, 4.0)),
|
|
54
|
+
Shape.TRIANGLE((6.0, 2.0))]
|
|
55
|
+
|
|
56
|
+
[area(s) for s in shapes] # [12.57, 12.0, 6.0]
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
This is one of my favorite features from [Swift](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/enumerations/#Associated-Values) and [Rust](https://doc.rust-lang.org/rust-by-example/custom_types/enum.html) so I brought it to Python ๐.
|
|
60
|
+
|
|
61
|
+
## โฌ Installation
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
pip install tagged-enum
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Requires Python 3.11+
|
|
68
|
+
|
|
69
|
+
## ๐ค How to use
|
|
70
|
+
|
|
71
|
+
Each uppercase attribute on a `TaggedEnum` subclass declares a *case*. The
|
|
72
|
+
value assigned to it is the *type* of payload that case carries. `None`
|
|
73
|
+
means the case carries nothing.
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
class GameEvent(TaggedEnum):
|
|
77
|
+
PLAYER_JOINED = str # player name
|
|
78
|
+
DAMAGE_DEALT = tuple[str, int] # target, amount
|
|
79
|
+
GAME_OVER = None # void
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Calling a case constructs an **instance**, and the payload is checked against
|
|
83
|
+
the declared type on instantiation.
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
GameEvent.PLAYER_JOINED("Ada") # ๐
|
|
87
|
+
GameEvent.DAMAGE_DEALT(("Jeff", 42)) # ๐
|
|
88
|
+
GameEvent.GAME_OVER() # ๐
|
|
89
|
+
GameEvent.PLAYER_JOINED(-1) # ๐ - TypeError
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
### ๐งฉ Typing
|
|
93
|
+
|
|
94
|
+
Payload declarations may be plain types, generic containers, unions, custom types, or forward references to the enclosing class for recursive structures:
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
class Json(TaggedEnum):
|
|
98
|
+
NULL = None
|
|
99
|
+
NUMBER = float
|
|
100
|
+
STRING = str
|
|
101
|
+
ARRAY = list["Json"]
|
|
102
|
+
OBJECT = dict[str, "Json"]
|
|
103
|
+
CUSTOM = MyDataclass
|
|
104
|
+
|
|
105
|
+
Json.OBJECT({
|
|
106
|
+
"name": Json.STRING("Ada"),
|
|
107
|
+
"tags": Json.ARRAY([Json.STRING("math"), Json.NUMBER(1815.0)]),
|
|
108
|
+
"other": Json.CUSTOM(MyDataclass())
|
|
109
|
+
})
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
`Union[...]` or `X | Y` and `Optional[...]` payloads are also valid types. Construction succeeds if the value matches any member of the union:
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
class ID(TaggedEnum):
|
|
116
|
+
VALUE = int | str
|
|
117
|
+
|
|
118
|
+
ID.VALUE(42) # ๐
|
|
119
|
+
ID.VALUE("abc") # ๐
|
|
120
|
+
ID.VALUE(4.2) # ๐ - TypeError
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Type checking validates the outer container (e.g. `list`, `dict`, which
|
|
124
|
+
member of a `Union`) but does not recurse into generic type parameters, and
|
|
125
|
+
skips validation entirely for unresolved forward references like `"Json"`
|
|
126
|
+
above.
|
|
127
|
+
|
|
128
|
+
### โจ Pattern Matching
|
|
129
|
+
|
|
130
|
+
Tagged enums are unpacked with Python's native [match statement](https://docs.python.org/3/tutorial/controlflow.html#match-statements) using the `kind`/`payload` attributes:
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
def handle(event: GameEvent) -> str:
|
|
134
|
+
match event:
|
|
135
|
+
case GameEvent(kind=GameEvent.PLAYER_JOINED, payload=name):
|
|
136
|
+
return f"{name} joined the game"
|
|
137
|
+
case GameEvent(kind=GameEvent.DAMAGE_DEALT, payload=(target, amount)):
|
|
138
|
+
return f"{target} took {amount} damage"
|
|
139
|
+
case GameEvent(kind=GameEvent.GAME_OVER):
|
|
140
|
+
return "Game over"
|
|
141
|
+
|
|
142
|
+
handle(GameEvent.DAMAGE_DEALT(("Grendel", 42)))
|
|
143
|
+
# 'Grendel took 42 damage'
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
When you only care about which case you're looking at and not the payload, use `.kind` to return the tag itself (also called the **member**):
|
|
147
|
+
|
|
148
|
+
```python
|
|
149
|
+
if event.kind is GameEvent.Kind.PLAYER_JOINED:
|
|
150
|
+
print("player joined")
|
|
151
|
+
|
|
152
|
+
match event.kind:
|
|
153
|
+
case GameEvent.Kind.PLAYER_JOINED:
|
|
154
|
+
...
|
|
155
|
+
case GameEvent.Kind.GAME_OVER:
|
|
156
|
+
...
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
`GameEvent.PLAYER_JOINED` (the **member**) and
|
|
160
|
+
`GameEvent.PLAYER_JOINED(...)` (an **instance**) are different objects and ideas. The member is a singleton tag you compare with `is`, while the instance carries the actual data payload. Members and instances are not equal (by `==`). Instances of the same kind/case are equal if and only if their payload values are equal.
|
|
161
|
+
|
|
162
|
+
The `Kind` type attribute is a type-level alias for annotating variables that should hold a case rather than an instance.
|
|
163
|
+
|
|
164
|
+
```python
|
|
165
|
+
def describe(kind: GameEvent.Kind) -> str:
|
|
166
|
+
if kind is GameEvent.Kind.PLAYER_JOINED:
|
|
167
|
+
do_something()
|
|
168
|
+
|
|
169
|
+
describe(event.kind) # 'damage was dealt'
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
## ๐ค Development
|
|
173
|
+
|
|
174
|
+
This project uses [`uv`](https://docs.astral.sh/uv/) for dependency management.
|
|
175
|
+
|
|
176
|
+
```bash
|
|
177
|
+
uv sync
|
|
178
|
+
uv run pytest
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
### Building
|
|
182
|
+
|
|
183
|
+
Build the sdist/wheel into `dist/`:
|
|
184
|
+
|
|
185
|
+
```bash
|
|
186
|
+
uv build
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
To try the library locally without installing it anywhere:
|
|
190
|
+
|
|
191
|
+
```bash
|
|
192
|
+
# drop into a REPL
|
|
193
|
+
uv run python
|
|
194
|
+
# OR run a script inside the project's environment
|
|
195
|
+
uv run python my_script.py
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
### ๐งช Testing
|
|
199
|
+
|
|
200
|
+
Tests live in `tests/`, split by topic (construction, equality/hashing,
|
|
201
|
+
pattern matching, generic payloads, etc.) so a single area can be run in
|
|
202
|
+
isolation, e.g.:
|
|
203
|
+
|
|
204
|
+
```bash
|
|
205
|
+
uv run pytest tests/test_generic_payloads.py
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
Without `uv`, the equivalent is:
|
|
209
|
+
|
|
210
|
+
```bash
|
|
211
|
+
pip install -e ".[test]"
|
|
212
|
+
pytest
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
## ๐ ๏ธ Contribution Guidelines
|
|
216
|
+
|
|
217
|
+
This repository is open source, though maintenance is infrequent. Please be
|
|
218
|
+
patient ๐ฅบ.
|
|
219
|
+
|
|
220
|
+
- **File an issue first:** Anything beyond a small fix should be discussed in an issue
|
|
221
|
+
before you put work into a PR.
|
|
222
|
+
- **Keep PRs focused:** One change or feature per PR, branched off `Development`
|
|
223
|
+
and rebased/updated before you submit.
|
|
224
|
+
- **Branch naming:** `issues/<issue-number>`, optionally with a short
|
|
225
|
+
description, e.g. `issues/123-fix-a-bug`.
|
|
226
|
+
- **Include a description and test coverage:** Explain what changed and
|
|
227
|
+
why, add or update tests under `tests/`, and reference the issue it
|
|
228
|
+
closes.
|
|
229
|
+
|
|
230
|
+
Thanks for helping keep this repo clean and organized! ๐
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
# tagged-enum
|
|
2
|
+
|
|
3
|
+
Tagged enums for Python ๐.
|
|
4
|
+
|
|
5
|
+
Tagged enums (a.k.a. discriminated unions, enums with associated values, etc.)
|
|
6
|
+
are enums where each case carries a typed **payload**.
|
|
7
|
+
|
|
8
|
+
```python
|
|
9
|
+
from tagged_enum import TaggedEnum
|
|
10
|
+
|
|
11
|
+
# Declare a tagged enum
|
|
12
|
+
class Shape(TaggedEnum):
|
|
13
|
+
CIRCLE = float # radius
|
|
14
|
+
RECTANGLE = tuple[float, float] # width, height
|
|
15
|
+
TRIANGLE = tuple[float, float] # base, height
|
|
16
|
+
|
|
17
|
+
def area(shape: Shape) -> float:
|
|
18
|
+
# match over enum cases
|
|
19
|
+
match shape:
|
|
20
|
+
case Shape(kind=Shape.CIRCLE, payload=radius):
|
|
21
|
+
return 3.14159 * radius ** 2
|
|
22
|
+
case Shape(kind=Shape.RECTANGLE, payload=(w, h)):
|
|
23
|
+
return w * h
|
|
24
|
+
case Shape(kind=Shape.TRIANGLE, payload=(b, h)):
|
|
25
|
+
return 0.5 * b * h
|
|
26
|
+
|
|
27
|
+
shapes = [Shape.CIRCLE(2.0),
|
|
28
|
+
Shape.RECTANGLE((3.0, 4.0)),
|
|
29
|
+
Shape.TRIANGLE((6.0, 2.0))]
|
|
30
|
+
|
|
31
|
+
[area(s) for s in shapes] # [12.57, 12.0, 6.0]
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
This is one of my favorite features from [Swift](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/enumerations/#Associated-Values) and [Rust](https://doc.rust-lang.org/rust-by-example/custom_types/enum.html) so I brought it to Python ๐.
|
|
35
|
+
|
|
36
|
+
## โฌ Installation
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install tagged-enum
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Requires Python 3.11+
|
|
43
|
+
|
|
44
|
+
## ๐ค How to use
|
|
45
|
+
|
|
46
|
+
Each uppercase attribute on a `TaggedEnum` subclass declares a *case*. The
|
|
47
|
+
value assigned to it is the *type* of payload that case carries. `None`
|
|
48
|
+
means the case carries nothing.
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
class GameEvent(TaggedEnum):
|
|
52
|
+
PLAYER_JOINED = str # player name
|
|
53
|
+
DAMAGE_DEALT = tuple[str, int] # target, amount
|
|
54
|
+
GAME_OVER = None # void
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Calling a case constructs an **instance**, and the payload is checked against
|
|
58
|
+
the declared type on instantiation.
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
GameEvent.PLAYER_JOINED("Ada") # ๐
|
|
62
|
+
GameEvent.DAMAGE_DEALT(("Jeff", 42)) # ๐
|
|
63
|
+
GameEvent.GAME_OVER() # ๐
|
|
64
|
+
GameEvent.PLAYER_JOINED(-1) # ๐ - TypeError
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### ๐งฉ Typing
|
|
68
|
+
|
|
69
|
+
Payload declarations may be plain types, generic containers, unions, custom types, or forward references to the enclosing class for recursive structures:
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
class Json(TaggedEnum):
|
|
73
|
+
NULL = None
|
|
74
|
+
NUMBER = float
|
|
75
|
+
STRING = str
|
|
76
|
+
ARRAY = list["Json"]
|
|
77
|
+
OBJECT = dict[str, "Json"]
|
|
78
|
+
CUSTOM = MyDataclass
|
|
79
|
+
|
|
80
|
+
Json.OBJECT({
|
|
81
|
+
"name": Json.STRING("Ada"),
|
|
82
|
+
"tags": Json.ARRAY([Json.STRING("math"), Json.NUMBER(1815.0)]),
|
|
83
|
+
"other": Json.CUSTOM(MyDataclass())
|
|
84
|
+
})
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
`Union[...]` or `X | Y` and `Optional[...]` payloads are also valid types. Construction succeeds if the value matches any member of the union:
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
class ID(TaggedEnum):
|
|
91
|
+
VALUE = int | str
|
|
92
|
+
|
|
93
|
+
ID.VALUE(42) # ๐
|
|
94
|
+
ID.VALUE("abc") # ๐
|
|
95
|
+
ID.VALUE(4.2) # ๐ - TypeError
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Type checking validates the outer container (e.g. `list`, `dict`, which
|
|
99
|
+
member of a `Union`) but does not recurse into generic type parameters, and
|
|
100
|
+
skips validation entirely for unresolved forward references like `"Json"`
|
|
101
|
+
above.
|
|
102
|
+
|
|
103
|
+
### โจ Pattern Matching
|
|
104
|
+
|
|
105
|
+
Tagged enums are unpacked with Python's native [match statement](https://docs.python.org/3/tutorial/controlflow.html#match-statements) using the `kind`/`payload` attributes:
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
def handle(event: GameEvent) -> str:
|
|
109
|
+
match event:
|
|
110
|
+
case GameEvent(kind=GameEvent.PLAYER_JOINED, payload=name):
|
|
111
|
+
return f"{name} joined the game"
|
|
112
|
+
case GameEvent(kind=GameEvent.DAMAGE_DEALT, payload=(target, amount)):
|
|
113
|
+
return f"{target} took {amount} damage"
|
|
114
|
+
case GameEvent(kind=GameEvent.GAME_OVER):
|
|
115
|
+
return "Game over"
|
|
116
|
+
|
|
117
|
+
handle(GameEvent.DAMAGE_DEALT(("Grendel", 42)))
|
|
118
|
+
# 'Grendel took 42 damage'
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
When you only care about which case you're looking at and not the payload, use `.kind` to return the tag itself (also called the **member**):
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
if event.kind is GameEvent.Kind.PLAYER_JOINED:
|
|
125
|
+
print("player joined")
|
|
126
|
+
|
|
127
|
+
match event.kind:
|
|
128
|
+
case GameEvent.Kind.PLAYER_JOINED:
|
|
129
|
+
...
|
|
130
|
+
case GameEvent.Kind.GAME_OVER:
|
|
131
|
+
...
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
`GameEvent.PLAYER_JOINED` (the **member**) and
|
|
135
|
+
`GameEvent.PLAYER_JOINED(...)` (an **instance**) are different objects and ideas. The member is a singleton tag you compare with `is`, while the instance carries the actual data payload. Members and instances are not equal (by `==`). Instances of the same kind/case are equal if and only if their payload values are equal.
|
|
136
|
+
|
|
137
|
+
The `Kind` type attribute is a type-level alias for annotating variables that should hold a case rather than an instance.
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
def describe(kind: GameEvent.Kind) -> str:
|
|
141
|
+
if kind is GameEvent.Kind.PLAYER_JOINED:
|
|
142
|
+
do_something()
|
|
143
|
+
|
|
144
|
+
describe(event.kind) # 'damage was dealt'
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
## ๐ค Development
|
|
148
|
+
|
|
149
|
+
This project uses [`uv`](https://docs.astral.sh/uv/) for dependency management.
|
|
150
|
+
|
|
151
|
+
```bash
|
|
152
|
+
uv sync
|
|
153
|
+
uv run pytest
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### Building
|
|
157
|
+
|
|
158
|
+
Build the sdist/wheel into `dist/`:
|
|
159
|
+
|
|
160
|
+
```bash
|
|
161
|
+
uv build
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
To try the library locally without installing it anywhere:
|
|
165
|
+
|
|
166
|
+
```bash
|
|
167
|
+
# drop into a REPL
|
|
168
|
+
uv run python
|
|
169
|
+
# OR run a script inside the project's environment
|
|
170
|
+
uv run python my_script.py
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
### ๐งช Testing
|
|
174
|
+
|
|
175
|
+
Tests live in `tests/`, split by topic (construction, equality/hashing,
|
|
176
|
+
pattern matching, generic payloads, etc.) so a single area can be run in
|
|
177
|
+
isolation, e.g.:
|
|
178
|
+
|
|
179
|
+
```bash
|
|
180
|
+
uv run pytest tests/test_generic_payloads.py
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Without `uv`, the equivalent is:
|
|
184
|
+
|
|
185
|
+
```bash
|
|
186
|
+
pip install -e ".[test]"
|
|
187
|
+
pytest
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
## ๐ ๏ธ Contribution Guidelines
|
|
191
|
+
|
|
192
|
+
This repository is open source, though maintenance is infrequent. Please be
|
|
193
|
+
patient ๐ฅบ.
|
|
194
|
+
|
|
195
|
+
- **File an issue first:** Anything beyond a small fix should be discussed in an issue
|
|
196
|
+
before you put work into a PR.
|
|
197
|
+
- **Keep PRs focused:** One change or feature per PR, branched off `Development`
|
|
198
|
+
and rebased/updated before you submit.
|
|
199
|
+
- **Branch naming:** `issues/<issue-number>`, optionally with a short
|
|
200
|
+
description, e.g. `issues/123-fix-a-bug`.
|
|
201
|
+
- **Include a description and test coverage:** Explain what changed and
|
|
202
|
+
why, add or update tests under `tests/`, and reference the issue it
|
|
203
|
+
closes.
|
|
204
|
+
|
|
205
|
+
Thanks for helping keep this repo clean and organized! ๐
|