How to use Python's enum module
· Category: Python Programming
Short answer
Python's enum module lets you define symbolic names bound to unique, constant values. Use enum.Enum to group related constants so your code is more readable and less error-prone than raw strings or integers.
Details
The enum module is part of the standard library and supports functional and class-based syntax. A basic example looks like this:
from enum import Enum
class Status(Enum):
PENDING = 1
APPROVED = 2
REJECTED = 3
Enums provide identity checking, automatic duplication prevention, and iterable membership. You can also use IntEnum or Flag when you need compatibility with integers or bitwise operations. In larger projects, enums pair well with Python type hints and clean class design to make APIs self-documenting. If you need to map configuration states or error codes, consider combining enums with Python dictionaries for fast lookups.
Tips
- Use
@enum.uniqueto enforce that no two members share the same value. - Prefer
auto()fromenumto let Python assign values automatically. - Access members by name (
Status.PENDING) rather than raw values to keep refactoring safe.