Using enums in programming is a way to define a set of named constants, which makes our code more readable and maintainable. In Python, enums were introduced in Python 3.4 through the enum
module. Here's how we can use enums in Python:
Step 1: Import the Enum class
First, we need to import the Enum
class from the enum
module.
from enum import Enum
Step 2: Define an Enum
We can define an enum by subclassing the Enum
class. Enum members are defined as class attributes.
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
Step 3: Using Enum Members
We can access enum members by their name or value, and we can also iterate over them.
# Access by name
print(Color.RED)
# Access by value
print(Color(1))
# Iterate over enum members
for color in Color:
print(color)
Enum Members
Enum members are instances of their enum class, and they're singletons. Each member has two properties: name
(the name of the member) and value
(the value assigned to it).
color = Color.RED
print(color.name) # Outputs: RED
print(color.value) # Outputs: 1
Comparing Enums
Enum members are unique and can be compared using identity (is
) and equality (==
) operators.
assert Color.GREEN is Color.GREEN
assert Color.GREEN == Color.GREEN
assert Color.GREEN is not Color.RED
In summary, using enums makes our code cleaner and more understandable, especially when dealing with a set of constants that represent a specific set of choices.
Thanks for reading another edition of Everything Python! Subscribe for free to receive new posts and support my work.