Strictly match all the possibilities of an enum
Project description
enumatch
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
from enum import Enum, auto
from enumatch import match
class 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
from enum import Enum, auto
from enumatch import match, forall
class 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
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
enumatch-0.2.0.tar.gz
(3.5 kB
view details)
Built Distribution
File details
Details for the file enumatch-0.2.0.tar.gz
.
File metadata
- Download URL: enumatch-0.2.0.tar.gz
- Upload date:
- Size: 3.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.0.5 CPython/3.7.6 Darwin/19.6.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 46cdd8b9e60d58e3d1c972ce4fd58baf51d43f026cfa616dc0bec4584ff9d39e |
|
MD5 | 724acdd351be7a5730324008078c236f |
|
BLAKE2b-256 | eab01ecf57e77a1d1affbe9765ee47eb21e5645768046543fa9ed5363d63294f |
File details
Details for the file enumatch-0.2.0-py3-none-any.whl
.
File metadata
- Download URL: enumatch-0.2.0-py3-none-any.whl
- Upload date:
- Size: 3.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.0.5 CPython/3.7.6 Darwin/19.6.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 90b325e8af45129b0723f298f9dbd0babc15c250d8f5a24669431ece282d05ca |
|
MD5 | 8daaef5663dbca497aeea6d01dacf9b7 |
|
BLAKE2b-256 | 383af2bc238f4de524b01588bb3613c77ce9068b54be72b95ef4f60d02eafebf |