Skip to main content

Strictly match all the possibilities of an enum

Project description

enumatch

PyPI version PyPI pyversions 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 explicitely or by using a default value.

Use ... (ellipsis) for default.

TIP: Create the matcher at compile-time to have zero runtime cost.

Example

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"})

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.1.3.tar.gz (2.9 kB view hashes)

Uploaded Source

Built Distribution

enumatch-0.1.3-py3-none-any.whl (3.1 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page