In Python, an enumeration (enum) is a symbolic name for a set of values. Enums are used to create named constant values, which makes the code more readable and maintainable. Python provides an Enum
class in the enum
module to create enumerations.
Here’s a simple example:
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
In this example, Color
is an enumeration with three members: RED
, GREEN
, and BLUE
, each assigned a numeric value. You can access these values using dot notation, like Color.RED
or Color.BLUE
.
print(Color.RED) # Output: Color.RED
print(Color.RED.value) # Output: 1
Enums can also be iterated:
for color in Color:
print(color)
This will output:
Color.RED
Color.GREEN
Color.BLUE
Enums provide a way to define named values, which can be more expressive and self-documenting than using raw integers or strings. They help prevent errors that might occur when using arbitrary values and provide a convenient way to represent a fixed set of options or states in your code.