https://github.com/lewisgaul/python_adt
Implementation of Alegbraic Data Types (ADTs) in Python
https://github.com/lewisgaul/python_adt
algebraic-data-types python3 sum-types tagged-unions
Last synced: 4 months ago
JSON representation
Implementation of Alegbraic Data Types (ADTs) in Python
- Host: GitHub
- URL: https://github.com/lewisgaul/python_adt
- Owner: LewisGaul
- License: mit
- Created: 2021-02-20T22:33:04.000Z (over 5 years ago)
- Default Branch: main
- Last Pushed: 2025-02-17T23:19:21.000Z (over 1 year ago)
- Last Synced: 2025-12-21T19:38:45.541Z (7 months ago)
- Topics: algebraic-data-types, python3, sum-types, tagged-unions
- Language: Python
- Homepage: https://adt.readthedocs.io
- Size: 39.1 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 5
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://github.com/LewisGaul/python_adt/actions/workflows/basic-tests.yml?query=branch%3Amain)
[](https://codecov.io/gh/LewisGaul/python_adt/)
[](https://adt.readthedocs.io/en/latest/?badge=latest)
# Algebraic Data Types in Python
```python
import adt
class MyADT(adt.ADT):
foo: ()
bar: (int,)
baz: (int, bool, str, None)
@adt.fieldmethod
def double_first(field, basecls) -> "MyADT":
if isinstance(field, basecls.foo):
raise TypeError(
f"{basecls.foo.__qualname__} does not support doubling"
)
field_type = type(field)
first, *rem = field
return field_type(first * 2, *rem)
foo = MyADT.foo()
bar = MyADT.bar(4)
baz = MyADT.baz(3, False, "hi", None)
for val in [foo, bar, baz]:
print(val)
try:
doubled = val.double_first()
print("Doubled:", doubled)
except TypeError:
print("Failed to double")
print()
```
See `examples/`, `adt/example.py` and `tests/test.py`.