enum
The Python enum
module provides support for enumerations, which are collections of constant values known as members.
Enumerations can improve code readability and maintainability by replacing literal constants and magic numbers with meaningful names.
Here’s how to create an enumeration:
>>> from enum import Enum
>>> class Color(Enum):
... RED = 1
... GREEN = 2
... BLUE = 3
...
>>> Color.RED
<Color.RED: 1>
Key Features
- Defines a series of named values
- Provides unique names to identify constant values
- Supports iteration and comparison
Frequently Used Classes and Functions
Object | Type | Description |
---|---|---|
Enum |
Class | Creates enumerations |
IntEnum |
Class | Creates enumerations where members must be integers |
StrEnum |
Class | Creates enumerations where members must be strings |
auto() |
Function | Automatically assigns values to members |
Note: The StrEnum
class was introduced in Python 3.11. It is not available if you’re using an earlier Python version.
Examples
Defining an enumeration for colors:
>>> from enum import Enum
>>> class Day(Enum):
... MONDAY = 1
... TUESDAY = 2
... WEDNESDAY = 3
... THURSDAY = 4
... FRIDAY = 5
... SATURDAY = 6
... SUNDAY = 7
...
Iterating over the members of an enumeration:
>>> for day in Day:
... print(day)
...
Day.MONDAY
Day.TUESDAY
Day.WEDNESDAY
Day.THURSDAY
Day.FRIDAY
Day.SATURDAY
Day.SUNDAY
Common Use Cases
- Defining a series of related constants with descriptive names
- Ensuring constant names are unique and members are immutable
- Facilitating comparison operations between related constants
Real-World Example
Suppose you’re developing a traffic light control system and need to define the states of a traffic light. You can use the enum
module to create an enumeration for this purpose. Here’s an example:
>>> from enum import Enum, auto
>>> class TrafficLight(Enum):
... RED = auto()
... YELLOW = auto()
... GREEN = auto()
>>> def can_go(light):
... return light == TrafficLight.GREEN
...
>>> current_light = TrafficLight.RED
>>> can_go(current_light)
False
In this example, the enum
module allows you to define the traffic light states clearly and use them in a function to determine if traffic can proceed, improving code clarity and maintainability.
Related Resources
Tutorial
Build Enumerations of Constants With Python's Enum
In this tutorial, you'll learn how to create and use enumerations of semantically related constants in Python. To do this, you'll use the Enum class and other related tools and types from the enum module, which is available in the Python standard library.
For additional information on related topics, take a look at the following resources:
By Leodanis Pozo Ramos • Updated July 1, 2025