Skip to main content

enumplus — Enhanced Enums for Python

PyPI Python License Tests

Python's enum.Enum is basic. enumplus adds display names, metadata, JSON serialization, choices(), and value-based comparison — all with zero runtime dependencies and full stdlib compatibility. Just change your import and everything still works.

Contents

Installation

pip install enumplus

For Pydantic v2 integration:

pip install "enumplus[pydantic]"

Requirements

  • Python 3.11 or higher
  • No runtime dependencies (Pydantic is optional and only required for Pydantic integration)

Quick Start

from enumplus import Enum

class Color(Enum):
    RED = ("red", {"label": "Red", "hex": "#FF0000"})
    GREEN = ("green", {"label": "Green", "hex": "#00FF00"})
    BLUE = "blue"  # no metadata needed

# Display names
print(Color.RED.label)          # "Red"
print(str(Color.RED))           # "Red"

# Metadata access
print(Color.RED.hex)            # "#FF0000"
print(Color.RED.metadata)       # {"label": "Red", "hex": "#FF0000"}

# choices() for forms/dropdowns
print(Color.choices())          # [("red", "Red"), ("green", "Green"), ("blue", "Blue")]

# Lookup by value
print(Color.from_value("red"))  # Color.RED

# Compare with values directly
print(Color.RED == "red")       # True

# Membership test
print("red" in Color)           # True

Features

Display Names (label)

Every member gets a human-readable label, auto-generated from the member name or set explicitly via metadata. Auto-generated labels replace underscores with spaces (IN_PROGRESS becomes "In Progress").

class Status(Enum):
    PENDING = "pending"         # label: "Pending"
    IN_PROGRESS = "in_progress" # label: "In Progress"

print(Status.PENDING.label)       # "Pending"
print(Status.IN_PROGRESS.label)   # "In Progress"
print(str(Status.IN_PROGRESS))    # "In Progress"

Metadata

Attach arbitrary metadata to enum members using (value, dict) tuples. Access via attribute or the metadata property.

class Color(Enum):
    RED = ("red", {"hex": "#FF0000", "description": "Pure red"})

print(Color.RED.hex)           # "#FF0000"
print(Color.RED.description)   # "Pure red"
print(Color.RED.metadata)      # {"hex": "#FF0000", "description": "Pure red"}

choices()

Returns a list of (value, label) tuples — perfect for forms and dropdowns.

class Priority(Enum):
    LOW = 1
    MEDIUM = 2
    HIGH = 3

print(Priority.choices())   # [(1, "Low"), (2, "Medium"), (3, "High")]

from_value() / from_name()

Look up members by value or name, with optional defaults and case-insensitive matching.

class Color(Enum):
    RED = "red"
    GREEN = "green"

Color.from_value("red")              # Color.RED
Color.from_value("blue")             # raises ValueError
Color.from_value("blue", default=None)  # None

# Case-insensitive lookup
Color.from_value("Red", case_insensitive=True)   # Color.RED
Color.from_value("GREEN", case_insensitive=True) # Color.GREEN

Color.from_name("RED")               # Color.RED
Color.from_name("BLUE", default=None)   # None

# Case-insensitive name lookup
Color.from_name("red", case_insensitive=True)   # Color.RED

is_valid() / validate()

Check if a value is valid, or validate and raise.

class Color(Enum):
    RED = "red"

Color.is_valid("red")       # True
Color.is_valid("blue")      # False
Color.is_valid(Color.RED)   # True

Color.validate("red")       # Color.RED
Color.validate("blue")      # raises ValueError

values() / names() / labels() / keys()

Get lists of all values, names, or labels. keys() is an alias of names() for dict-like ergonomics.

class Color(Enum):
    RED = ("red", {"label": "Red"})
    GREEN = ("green", {"label": "Green"})

Color.values()   # ["red", "green"]
Color.names()    # ["RED", "GREEN"]
Color.labels()   # ["Red", "Green"]
Color.keys()     # ["RED", "GREEN"]

filter()

Filter members by metadata key-value pairs (AND logic). label is special: it matches against the evaluated label (including auto-generated and callable labels), not the raw metadata dict.

class Color(Enum):
    RED = ("red", {"hex": "#FF0000", "category": "warm"})
    GREEN = ("green", {"hex": "#00FF00", "category": "cool"})

Color.filter(category="warm")              # [Color.RED]
Color.filter(hex="#FF0000", category="warm")  # [Color.RED]
Color.filter()                             # [Color.RED, Color.GREEN]
Color.filter(label="Red")                  # [Color.RED]

Comparison with values (==)

Members compare equal to their values directly.

class Color(Enum):
    RED = "red"

Color.RED == "red"          # True
Color.RED == Color.RED      # True
Color.RED == "RED"          # False (name != value)
Color.RED != 42             # True

Membership test (in)

Check if a value or member belongs to an enum.

class Color(Enum):
    RED = "red"

"red" in Color          # True
"blue" not in Color     # True
Color.RED in Color      # True
42 not in Color         # True

OrderedEnum

Order members by declaration order using <, <=, >, >=.

from enumplus import OrderedEnum

class Priority(OrderedEnum):
    LOW = 1
    MEDIUM = 2
    HIGH = 3

Priority.LOW < Priority.HIGH    # True
Priority.HIGH > Priority.LOW    # True
sorted([Priority.HIGH, Priority.LOW, Priority.MEDIUM])  # [LOW, MEDIUM, HIGH]
min(Priority)   # Priority.LOW
max(Priority)   # Priority.HIGH

JSON Serialization (to_json / from_json)

Serialize an enum class to JSON and parse it back.

class Color(Enum):
    RED = ("red", {"hex": "#FF0000"})

json_str = Color.to_json()
# {
#   "name": "Color",
#   "members": [
#     {"name": "RED", "value": "red", "label": "Red", "metadata": {"hex": "#FF0000"}}
#   ]
# }

data = Color.from_json(json_str)   # parse back to dict

SerializableEncoder

Serialize enum members to their values in JSON via a custom encoder.

import json
from enumplus import Enum, SerializableEncoder

class Color(Enum):
    RED = "red"

json.dumps(Color.RED, cls=SerializableEncoder)           # '"red"'
json.dumps([Color.RED], cls=SerializableEncoder)         # '["red"]'
json.dumps({"color": Color.RED}, cls=SerializableEncoder)  # '{"color": "red"}'

Pydantic v2

enumplus works with Pydantic v2 out of the box. Members validate from values and serialize to values.

from pydantic import BaseModel
from enumplus import Enum

class Color(Enum):
    RED = "red"
    GREEN = "green"

class MyModel(BaseModel):
    color: Color

model = MyModel(color="red")     # validates "red" -> Color.RED
print(model.color)               # Color.RED
print(model.model_dump())        # {"color": "red"}
print(model.model_dump_json())   # '{"color":"red"}'

Serialize by name

Set serialize_by_name = True on the enum class to validate and serialize by member name instead of value.

from pydantic import BaseModel
from enumplus import Enum

class ColorByName(Enum):
    RED = "red"
    GREEN = "green"

    serialize_by_name = True

class MyModelByName(BaseModel):
    color: ColorByName

model = MyModelByName(color="RED")    # validates "RED" -> ColorByName.RED
print(model.model_dump())             # {"color": "RED"}
print(model.model_dump_json())        # '{"color":"RED"}'

get() with default

Dict-style lookup that returns None (or a custom default) instead of raising.

class Color(Enum):
    RED = "red"

Color.get("red")             # Color.RED
Color.get("blue")            # None
Color.get("blue", default=Color.RED)  # Color.RED

map()

Map each member to a value via a dictionary. Returns {name: mapped_value}.

class Color(Enum):
    RED = "red"
    GREEN = "green"

Color.map({Color.RED: "#FF0000", Color.GREEN: "#00FF00"})
# {"RED": "#FF0000", "GREEN": "#00FF00"}

Color.map({Color.RED: "#FF0000"})
# {"RED": "#FF0000", "GREEN": None}

get_initial() / get_final()

Get the first or last member by declaration order.

class Color(Enum):
    RED = "red"
    GREEN = "green"
    BLUE = "blue"

Color.get_initial()   # Color.RED
Color.get_final()     # Color.BLUE

to_dict()

Serialize the entire enum to a nested dictionary with value, label, and metadata per member.

class Color(Enum):
    RED = ("red", {"hex": "#FF0000"})
    GREEN = "green"

Color.to_dict()
# {
#   "RED": {"value": "red", "label": "Red", "metadata": {"hex": "#FF0000"}},
#   "GREEN": {"value": "green", "label": "Green", "metadata": {}}
# }

i18n / Translatable Labels

Labels can be callables (e.g. lambda functions) for dynamic, locale-aware translations. The label property evaluates the callable on every access.

translations = {"RED": "Rojo", "GREEN": "Verde"}

class Color(Enum):
    RED = ("red", {"label": lambda: translations["RED"]})
    GREEN = ("green", {"label": lambda: translations["GREEN"]})

print(Color.RED.label)     # "Rojo"
print(str(Color.RED))      # "Rojo"
print(Color.labels())      # ["Rojo", "Verde"]
print(Color.choices())     # [("red", "Rojo"), ("green", "Verde")]

Callable labels work everywhere: choices(), to_dict(), to_json(), labels(), filter(label=...), and str().

Type hints in metadata

Metadata attributes are resolved at runtime through __getattr__, which returns Any. Type checkers therefore accept member.<key> accesses as Any, but cannot verify individual key names or value types.

class Color(Enum):
    RED = ("red", {"hex": "#FF0000"})

Color.RED.hex  # inferred as Any via __getattr__

Migration from stdlib

Just change one import:

# Before
from enum import Enum

# After
from enumplus import Enum

All existing enum code continues to work — Enum["RED"], Enum("red"), list(Enum), len(Enum), @unique, auto(), isinstance checks, everything.

A few deliberate differences from enum.Enum to keep in mind:

  • str(member) returns the label, not "ClassName.MEMBER" (repr() shows <ClassName.MEMBER: value>), and member == value compares by value.
  • serialize_by_name is a reserved class attribute for Pydantic config — it can't be used as a member name and must be a bool.
  • Metadata keys that collide with real attributes (name, value, label, metadata) are only reachable via member.metadata, not as attributes.
  • Metadata declared on an alias is ignored — an alias shares the canonical member's label and metadata.

Changelog

See CHANGELOG.md for a full history of changes.

Contributing

Contributions are welcome! See CONTRIBUTING.md for guidelines on how to get started, code style, and pull request workflow.

License

MIT — see LICENSE for details.

Metadata

Release files for enumplus 1.2.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for enumplus 1.2.3
File Size Uploaded Provenance Actions
enumplus-1.2.3.tar.gz 35.7 kB With provenance Details for enumplus-1.2.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for enumplus 1.2.3
File Interpreter ABI Platform Actions
enumplus-1.2.3-py3-none-any.whl Python 3 none any Details for enumplus-1.2.3-py3-none-any.whl

Total release size: 50.2 kB

Release files / enumplus-1.2.3.tar.gz

Download URL enumplus-1.2.3.tar.gz
Size 35.7 kB
Tags Source
SHA-256 checksum
How to use checksums
7a318a230158ca264dca05ee58e33ef25f13750d3da0afe220b82ebdb77c18c2
BLAKE2b-256 checksum
How to use checksums
71682635717f3cac6eb76e7fb98724457cb2b2043847e82ba9d327958eb743a3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

Release files / enumplus-1.2.3-py3-none-any.whl

Download URL enumplus-1.2.3-py3-none-any.whl
Size 14.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4b234b1a744e0046ce530aae0e6eeb0911d09797bc0e54554fbee57be358113e
BLAKE2b-256 checksum
How to use checksums
2bdc9958f1f05884b5f2de61ad339e8cd9163303ad4648d339c837cc185a8a47
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

Security for enumplus 1.2.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for enumplus-1.2.3.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page