Skip to main content

Enum implementation that accepts unknown values.

Project description

OpenEnum

Enum implementation that accepts unknown values.

Rationale

When parsing external data into Python data types, sometimes we deal with enumerated data types which have several documented possible values, but should be parsed with assumption that more possible values will be added over time.

Code that reads such values should be written with forward compatibility in mind: handle all known values, but also include a fallback for any other values that can appear in the future. Options for doing this in Python include parsing as str, as EnumType | str or as EnumType with a _missing_ method defined.

This library attempts to provide a pattern for handling such values in a type-safe manner that plays well with existing linters.

Usage

Parsing possibly-unknown values

Define an OpenEnum subclass with one member value of None that will be used as fallback:

from open_enum import OpenEnum


class Status(OpenEnum):
    NEW = "new"
    IN_PROGRESS = "in_progress"
    DONE = "done"

    UNKNOWN = None

Normal values work intuitively:

new = Status.NEW
done = Status.DONE
assert Status("new") == new
assert Status("new") != done

But unlike normal enum, you can also instantiate the type with unknown values:

blocked = Status("blocked")
cancelled = Status("cancelled")
assert isinstance(blocked, Status)

These compare as different to each other:

assert blocked != new
assert blocked != cancelled

but still compare as equal if the underlying value matches:

assert blocked == Status("blocked")

Checking for unknown values using the UNKNOWN marker

The UNKNOWN value defined on the enum type is a special marker object, not an actual enum member:

assert not isinstance(Status.UNKNOWN, Status)

[!NOTE]
You'll never get Status.UNKNOWN from parsing; it's meant to be used explicitly.

The unknown marker compares as equal to unknown values, but not to known values:

assert Status.UNKNOWN == Status("blocked")
assert Status.UNKNOWN == Status("cancelled")

assert Status.UNKNOWN != Status("new")
assert Status.UNKNOWN != Status("in_progress")

Pattern matching

All this allows you to do exhaustive pattern matching that your linter will validate for you:

class Response:
    status: Status
    ...


match response.status:
    case Status.NEW:
        print("new!")
    case Status.IN_PROGRESS:
        print("in progress...")
    case Status.DONE:
        print("nothing more to do")
    case Status.UNKNOWN:
        print("oh, encountered a status we don't know!")
    case _:
        assert_never(response.status)

Now if you go back to class Status and add enum members for "blocked" or "cancelled", your type checker will ask you to add corresponding case arms in this match statement.

[!TIP] The main advantage of this pattern over just using case _ as fallback is that is that it communicates the intention that every known value should have a case branch. Thanks to assert_never, a type checker can actually check and enforce this!

Importantly, as long as you include assert_never, the type checker should nudge you to include a case for Status.UNKNOWN:

match response.status:
    case Status.NEW:
        print("new!")
    case Status.IN_PROGRESS:
        print("in progress...")
    case Status.DONE:
        print("nothing more to do")
    case _:
        assert_never(response.status)  # error: Type "Literal[Status.UNKNOWN]" is not assignable to type "Never"

This way as long as you remember about assert_never(), you'll have a helpful reminder to add handling of additional unknown values that can be added in the future, even if you already handled all values that are currently documented.

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

open_enum-0.2.1.tar.gz (4.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

open_enum-0.2.1-py3-none-any.whl (5.5 kB view details)

Uploaded Python 3

File details

Details for the file open_enum-0.2.1.tar.gz.

File metadata

  • Download URL: open_enum-0.2.1.tar.gz
  • Upload date:
  • Size: 4.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for open_enum-0.2.1.tar.gz
Algorithm Hash digest
SHA256 c040fae458d4d666d6da92beb44f4bac0fcee39590bf6c4468c8f1d9aa79728c
MD5 bd14397a36924d08cec7ab993cfcadb9
BLAKE2b-256 d7d3a7d7e768b14e55df5a2faa28d6075204eaf6c745717f237789d24ed5eecf

See more details on using hashes here.

File details

Details for the file open_enum-0.2.1-py3-none-any.whl.

File metadata

  • Download URL: open_enum-0.2.1-py3-none-any.whl
  • Upload date:
  • Size: 5.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for open_enum-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 2b5ee5496168bd4a1b7b2069a2372ab03cb6cf6afe6b9f81ec80152112a6f319
MD5 b97fcd1c10f5ba34604b92d3d8811bd3
BLAKE2b-256 f8532a768fb13d1512c2285ded1852fe4d666c7ba25fb939cd70d325fd2eec84

See more details on using hashes here.

Supported by

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