Featured


Introduction

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.

Importing the Enum class

First, you need to import the Enum class from the typing module.

from enum import Enum

Defining an 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

Using Enum

You can access the Enum members using the dot notation.

today = Day.WEDNESDAY
print(today)  # Output: Day.WEDNESDAY

Enum Iteration

You can iterate through all the Enum members using a loop.

for day in Day:
    print(day)