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.

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).

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]

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(), and str().

Type hints in metadata

The @dataclass_transform() decorator on the metaclass enables type checkers to recognize metadata fields.

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

# Type checkers recognize .hex as a valid attribute
Color.RED.hex  # inferred as Any via __getattr__

Note: Type inference for metadata attributes depends on the type checker. The @dataclass_transform() decorator provides the structural hint, but runtime attribute access goes through __getattr__, which returns Any.

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.

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.

Release files for enumplus 1.2.0

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.0
File Size Uploaded
enumplus-1.2.0.tar.gz 27.0 kB Details

Built distribution (wheel)

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

Total release size: 39.5 kB

Release files / enumplus-1.2.0.tar.gz

Download URL enumplus-1.2.0.tar.gz
Size 27.0 kB
Tags Source
SHA-256 checksum
How to use checksums
b2c9f3f68bb4b2f5045bda4d91177ec4729dae5aaecaed8dc0bdc8dc87e19851
BLAKE2b-256 checksum
How to use checksums
1487849c41fb4be9c963affd61a6bbe385e40e3122d38095f70b7ee3b4a79273
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 Aug 23, 2026.

Transparency log

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

Download URL enumplus-1.2.0-py3-none-any.whl
Size 12.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
015cfd14481a478d48df821079dd5a0da422016acfeddc9da4087a2147191597
BLAKE2b-256 checksum
How to use checksums
b69c89f22d48ad0052322cf227e669abd7b36e481a64b11f4a0e1a5708e6025a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 Aug 23, 2026.

Transparency log

Release history Release notifications | RSS feed

1.2.1

2 release files

This release

1.2.0 This release

2 release files

1.1.0

2 release files

1.0.0

2 release files

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