Featured
Certainly! Enums in the typing
module are a powerful way to define symbolic names for a set of values. They help make your code more readable and maintainable by providing a clear representation of possible values for a particular variable. Let's dive into a complete guide to using Enums in Python with examples and code walkthroughs.
Enum
classFirst, you need to import the Enum
class from the typing
module.
from enum import Enum
Enum
To define an Enum, create a subclass of Enum
and define your symbolic names as class attributes.
class Day(Enum):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
SUNDAY = 7
Enum
You can access the Enum members using the dot notation.
today = Day.WEDNESDAY
print(today) # Output: Day.WEDNESDAY
Enum
IterationYou can iterate through all the Enum members using a loop.
for day in Day:
print(day)