To represent an Enum
(enumeration) in Python, use the enum
module from the standard library. Enums provide a structured way to define named constants, improving code readability and type safety. Below is a detailed guide with examples:
1. Basic Enum Definition
Define an Enum
by subclassing Enum
and listing members as class attributes.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
# Usage
print(Color.RED) # Output: Color.RED
print(Color.RED.name) # Output: 'RED'
print(Color.RED.value) # Output: 1
2. Auto-Assigned Values
Use auto()
to automatically assign incremental values.
from enum import Enum, auto
class Priority(Enum):
LOW = auto() # Value: 1
MEDIUM = auto() # Value: 2
HIGH = auto() # Value: 3
print(Priority.HIGH.value) # Output: 3
3. Enums with String Values
Assign meaningful string values for clarity.
class HTTPMethod(Enum):
GET = "GET"
POST = "POST"
PUT = "PUT"
DELETE = "DELETE"
print(HTTPMethod.POST.value) # Output: 'POST'
4. Unique Values
Enforce unique values with the @unique
decorator.
from enum import Enum, unique
@unique
class Status(Enum):
PENDING = 1
RUNNING = 2
COMPLETED = 3 # Duplicate values will raise an error.
5. Iterating Over Enums
Loop through all members of an Enum
.
for color in Color:
print(color.name, color.value)
# Output:
# RED 1
# GREEN 2
# BLUE 3
6. Lookup by Value or Name
Retrieve members by their value or name.
# By value
print(Color(1)) # Output: Color.RED
# By name
print(Color['RED']) # Output: Color.RED
7. IntEnum for Integer Comparisons
Use IntEnum
to treat members as integers.
from enum import IntEnum
class Day(IntEnum):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
print(Day.MONDAY == 1) # Output: True
8. StrEnum (Python 3.11+)
Compare members directly to strings.
from enum import StrEnum
class LogLevel(StrEnum):
DEBUG = "DEBUG"
INFO = "INFO"
ERROR = "ERROR"
print(LogLevel.DEBUG == "DEBUG") # Output: True
9. Enums with Methods
Add custom methods to enums for additional functionality.
from enum import Enum
class Planet(Enum):
MERCURY = (3.303e23, 2.4397e6)
EARTH = (5.976e24, 6.378e6)
def __init__(self, mass, radius):
self.mass = mass # in kg
self.radius = radius # in meters
@property
def gravity(self):
G = 6.673e-11
return G * self.mass / (self.radius ** 2)
print(Planet.EARTH.gravity) # Output: ~9.798 m/s²
10. Enums in Practice
Use enums to validate function arguments.
def set_light(color: Color):
if not isinstance(color, Color):
raise ValueError("Invalid color")
print(f"Light set to {color.name}")
set_light(Color.RED) # Valid
set_light(1) # Raises ValueError
Key Features
Feature | Description |
---|---|
Named Constants | Improve code readability by replacing magic numbers/strings. |
Type Safety | Enforce valid values in function parameters. |
Unique Values | Prevent duplicates with @unique . |
Methods/Properties | Attach logic directly to enum members. |
Lookup | Retrieve members by name or value. |
When to Use Enums
- Represent a fixed set of constants (e.g., states, error codes, options).
- Replace ambiguous strings/integers with meaningful names.
- Validate inputs in functions/APIs.
Summary
- Use
Enum
for general-purpose named constants. - Use
IntEnum
/StrEnum
for integer/string comparisons. - Decorate with
@unique
to enforce unique values. - Add methods to encapsulate member-specific logic.
Enums make your code more robust and self-documenting.