https://github.com/sayanarijit/enumatch
Strictly match all the possibilities of an enum
https://github.com/sayanarijit/enumatch
enum functional python3
Last synced: 6 months ago
JSON representation
Strictly match all the possibilities of an enum
- Host: GitHub
- URL: https://github.com/sayanarijit/enumatch
- Owner: sayanarijit
- License: mit
- Created: 2020-11-20T17:27:00.000Z (almost 5 years ago)
- Default Branch: master
- Last Pushed: 2020-11-23T11:06:54.000Z (almost 5 years ago)
- Last Synced: 2025-03-11T00:07:43.845Z (7 months ago)
- Topics: enum, functional, python3
- Language: Python
- Homepage: https://pypi.org/p/enumatch
- Size: 22.5 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
enumatch
========[](https://pypi.org/project/enumatch)
[](https://pypi.org/project/enumatch)
[](https://codeclimate.com/github/sayanarijit/enumatch/test_coverage)Strictly match all the possibilities of an enum.
Use case
--------This little `match` function makes matching Python's enum fields safer by forcing
us to match all the possibilities either explicitly or by using a wildcard.Use `...` (ellipsis) for the wildcard.
> ***TIPs***
>
> - Avoid the use of `...` (wildcard) to make sure any modification to the enums are safe.
> - Create the matcher at compile-time to have compile-time validation and zero runtime cost.Example: Flat matcher
---------------------```python
from enum import Enum, auto
from enumatch import matchclass Side(Enum):
left = auto()
right = auto()# Define a simple matcher
matcher1 = match({Side.left: "Go left", Side.right: "Go right"})assert matcher1[Side.left] == "Go left"
assert matcher1[Side.right] == "Go right"# Define a matcher with a default case
matcher2 = match({Side.left: "Go left", ...: "Go right"})assert matcher2[Side.left] == "Go left"
assert matcher2[Side.right] == "Go right"# If all the possibilities are not handled, we get error
with pytest.raises(ValueError, match="missing possibilities: Side.right"):
match({Side.left: "Go left"})
```Example: Nested matcher
-----------------------```python
from enum import Enum, auto
from enumatch import match, forallclass Switch(Enum):
on = auto()
off = auto()# is_on[main_switch][bedroom_switch]: bool
is_on = match({
Switch.on: match({Switch.on: True, Switch.off: False}),
Switch.off: forall(Switch, False),
})assert is_on[Switch.on][Switch.on] == True
assert is_on[Switch.on][Switch.off] == False
assert is_on[Switch.off][Switch.on] == False
assert is_on[Switch.off][Switch.off] == False
```