Python Enums & Constants
Model Fixed Choices Safely
Replace magic strings and fragile constants with Enum, IntEnum, Flag, and auto(). Eight interactive lessons with runnable examples β by @PoeticGlenn.
What you will learn
How to define readable, type-safe sets of named values; when to use IntEnum vs plain Enum; how bit flags work with Flag; and practical patterns for status codes, permissions, and configuration that stay maintainable.
Why Enums Belong in Modern Python
Most programs eventually need a fixed set of choices: status values ("pending", "approved", "rejected"),
permission levels, days of the week, HTTP methods, or feature flags. Using plain strings or integers works at first,
but it is easy to mistype a value, pass the wrong constant, or break code when a new option is added.
Pythonβs enum module (available since 3.4, improved in later versions) gives you a clean, readable way
to model those fixed choices. An Enum is a class whose members are the allowed values. Using an Enum member
instead of a string makes typos fail early, improves readability, and works well with type checkers and IDEs.
π€ The Problem Enums Solve
Magic strings and scattered constants create silent bugs
β Without Enums β Fragile Strings
Hard-coded strings are easy to mistype and hard to discover. Refactoring later means searching the whole codebase.
status = "pendng" # typo β no error until runtime logic fails def process(order_status): if order_status == "pending": return "waiting" elif order_status == "approved": return "done" return "unknown" print(process(status)) # silently wrong path
β With Enums β Safe Named Values
Members are defined once. Using a non-existent member raises an error at the point of use (or is caught by a type checker).
from enum import Enum class OrderStatus(Enum): PENDING = "pending" APPROVED = "approved" REJECTED = "rejected" def process(status: OrderStatus): if status is OrderStatus.PENDING: return "waiting" if status is OrderStatus.APPROVED: return "done" return "unknown" print(process(OrderStatus.PENDING)) print(OrderStatus.PENDING) print(OrderStatus.PENDING.value)
is when comparing Enum members β they are singletons. Use .value when you need the underlying data (string, int, etc.).π·οΈ Creating a Basic Enum
The simplest and most common form
π 1.1 Defining Members
Subclass Enum and assign values. Member names are conventionally UPPER_CASE.
Step-by-step explanation:
- Step 1: Import
Enumfrom theenummodule. - Step 2: Define a class that inherits from
Enum. - Step 3: Assign each member a unique value (string, int, or any hashable).
- Step 4: Access members with
ClassName.MEMBER. - Step 5: Use
.nameand.valueto inspect a member.
from enum import Enum class Color(Enum): RED = "red" GREEN = "green" BLUE = "blue" print(Color.RED) print(Color.RED.name) print(Color.RED.value) print(list(Color)) print(Color["GREEN"]) print(Color("blue"))
Color["GREEN"] looks up by name; Color("blue") looks up by value. Both raise KeyError / ValueError if the lookup fails.π 1.2 Iteration and Membership
Enums are iterable and support membership tests.
from enum import Enum class Direction(Enum): NORTH = 1 SOUTH = 2 EAST = 3 WEST = 4 for d in Direction: print(f"{d.name} β {d.value}") print(Direction.NORTH in Direction) print(5 in Direction) # False β 5 is not a member
β¨ Using auto()
Let Python assign values automatically
π 2.1 Automatic Integer Values
When the exact value does not matter, auto() assigns sequential integers starting at 1.
from enum import Enum, auto class Priority(Enum): LOW = auto() MEDIUM = auto() HIGH = auto() CRITICAL = auto() for p in Priority: print(f"{p.name}: {p.value}") print(Priority.HIGH is Priority.HIGH) print(Priority.HIGH == Priority.CRITICAL)
auto() values are generated in definition order. You can mix explicit values and auto(), but the behaviour is clearer when you stick to one style.π 2.2 Custom _generate_next_value_
Override how auto() generates values (for example, to produce lowercase names).
from enum import Enum, auto class Role(Enum): def _generate_next_value_(name, start, count, last_values): return name.lower() ADMIN = auto() EDITOR = auto() VIEWER = auto() print(Role.ADMIN.value) print(Role.EDITOR.value) print(list(Role))
π’ IntEnum β When Values Are Integers
Comparable and usable like integers
π 3.1 IntEnum Basics
IntEnum members behave like integers in comparisons and arithmetic. Useful for status codes and ordered levels.
from enum import IntEnum class HttpStatus(IntEnum): OK = 200 CREATED = 201 BAD_REQUEST = 400 NOT_FOUND = 404 SERVER_ERROR = 500 print(HttpStatus.OK == 200) print(HttpStatus.OK < HttpStatus.BAD_REQUEST) print(HttpStatus.NOT_FOUND + 1) print(isinstance(HttpStatus.OK, int))
IntEnum members are also int, they can be mixed with plain integers. Prefer plain Enum when you want to prevent accidental numeric comparison.π 3.2 IntEnum vs Enum
Plain Enum members with integer values are not integers β comparison with == against an int returns False.
from enum import Enum, IntEnum class Plain(Enum): A = 1 class AsInt(IntEnum): A = 1 print("Plain.A == 1 β", Plain.A == 1) print("AsInt.A == 1 β", AsInt.A == 1) print("type(Plain.A):", type(Plain.A)) print("type(AsInt.A):", type(AsInt.A))
π© Flag & IntFlag β Combinable Options
Bit flags for permissions, options, and feature sets
π 4.1 Defining Flags
Flag (and IntFlag) members can be combined with bitwise operators. Perfect for permission systems.
from enum import Flag, auto class Permission(Flag): READ = auto() WRITE = auto() EXECUTE = auto() ALL = READ | WRITE | EXECUTE user = Permission.READ | Permission.WRITE print(user) print(Permission.READ in user) print(Permission.EXECUTE in user) print(user & Permission.WRITE) print(bool(user & Permission.EXECUTE))
| to combine, & to test or intersect, and ~ to invert. IntFlag works the same way but members are also integers.π 4.2 Practical Permission Check
from enum import Flag, auto class Access(Flag): NONE = 0 READ = auto() WRITE = auto() DELETE = auto() ADMIN = READ | WRITE | DELETE def can_delete(user_access: Access) -> bool: return Access.DELETE in user_access guest = Access.READ editor = Access.READ | Access.WRITE admin = Access.ADMIN print("Guest can delete?", can_delete(guest)) print("Editor can delete?", can_delete(editor)) print("Admin can delete?", can_delete(admin)) print("Admin flags:", admin)
π οΈ Methods and Custom Behaviour
Enums can have methods and properties just like regular classes
π 5.1 Adding Methods to an Enum
Members can call instance methods. This keeps related logic next to the values.
from enum import Enum class Planet(Enum): MERCURY = (3.303e+23, 2.4397e6) EARTH = (5.976e+24, 6.37814e6) MARS = (6.421e+23, 3.3972e6) def __init__(self, mass, radius): self.mass = mass self.radius = radius @property def surface_gravity(self): G = 6.67300E-11 return G * self.mass / (self.radius ** 2) print(f"Earth gravity: {Planet.EARTH.surface_gravity:.2f} m/sΒ²") print(f"Mars gravity: {Planet.MARS.surface_gravity:.2f} m/sΒ²")
__init__ receives the unpacked values. This is a common pattern for richer Enum members.π 5.2 Functional API (less common)
You can also create Enums with the functional form when the set of members is generated at runtime.
from enum import Enum Animal = Enum("Animal", ["ANT", "BEE", "CAT", "DOG"]) print(list(Animal)) print(Animal.BEE) print(Animal.BEE.value) # With explicit values HttpMethod = Enum("HttpMethod", {"GET": "GET", "POST": "POST", "PUT": "PUT"}) print(HttpMethod.POST.value)
β Best Practices & Patterns
How to use Enums cleanly in real code
π Guidelines
- βUse
Enumfor sets of related named constants that should not be mixed with other types - βUse
IntEnumonly when integer behaviour (comparison, arithmetic) is genuinely needed - βPrefer
isover==when comparing Enum members (they are singletons) - βName members in UPPER_CASE to match PEP 8 for constants
- βPut the Enum definition near the code that uses it, or in a dedicated
constants.py/enums.py - βUse
Flagfor combinable options; avoid reinventing bit masks with plain integers - βFor simple one-off constants that are not a closed set, a module-level constant is still fine
π 6.1 Unique Values with @unique
Decorate the class with @unique to ensure no two members share the same value.
from enum import Enum, unique @unique class ErrorCode(Enum): SUCCESS = 0 NOT_FOUND = 404 FORBIDDEN = 403 # DUPLICATE = 404 # would raise ValueError at class creation print(ErrorCode.SUCCESS) print(ErrorCode.NOT_FOUND.value)
π 6.2 Using Enums in match (Python 3.10+)
from enum import Enum, auto class TrafficLight(Enum): RED = auto() YELLOW = auto() GREEN = auto() def action(light: TrafficLight) -> str: match light: case TrafficLight.RED: return "Stop" case TrafficLight.YELLOW: return "Caution" case TrafficLight.GREEN: return "Go" case _: return "Unknown" print(action(TrafficLight.GREEN)) print(action(TrafficLight.RED))
π Quick Navigation
Jump to any lesson
β Frequently Asked Questions
Common questions about Python Enums
Use an Enum when you have a closed set of related values that should be treated as a distinct type (status codes, roles, modes). For a single isolated constant, a module-level name is usually enough.
Prefer is. Enum members are singletons, so identity comparison is both correct and slightly more efficient. == also works for normal cases.
IntFlag members are also integers and can be mixed freely with int values. Flag members are not integers; this prevents accidental numeric operations. Prefer Flag unless you need the integer behaviour.
Yes. Values can be strings, integers, tuples, or any hashable object. When using tuples you can unpack them in __init__ to attach extra attributes to each member.
The enum module was added in Python 3.4. Flag and auto() improvements arrived later; this curriculum targets Python 3.10+ where the full modern API is available.
π Next Steps
You now have a solid working knowledge of Python Enums
β What You Covered
- Why Enums exist and the problems they solve with magic strings
- Creating basic Enums and looking up members by name or value
- Using
auto()and custom value generation - IntEnum for integer-compatible members
- Flag / IntFlag for combinable bit flags and permissions
- Adding methods and properties to Enum classes
- Best practices and using Enums with
match
Related modules on Poetic Bytes: Classes, Type Hints, and the main Curriculum.