Python Enums

Python enum (Enumerations)

Enum (short for enumerations) is a feature in Python that allows you to define a set of named values that are bound to unique constants. Each value in the enumeration is called a member, and it has both a name and a value. Enums can make code more readable and organized, especially when working with constant values that need to be grouped logically.

Why Use Enums?
Enums are useful in situations where you have a fixed set of related values that you need to represent in your code, such as days of the week, directions, states, or categories. They make the code more readable by giving these values meaningful names, rather than using arbitrary numbers or strings.
To create an enumeration, you use the Enum class from Python’s enum module.
Syntax:
from enum import Enum
class classname(Enum):
    const1 = val1
    const2 = val2
    const3 = val3
    const4 = val4

Example:
Creating and accessing enums

from enum import Enum
class Direction(Enum):
    NORTH = 1
    EAST = 2
    SOUTH = 3
    WEST = 4

# Access by name
print(Direction.NORTH)               # Output: Direction.NORTH
print(Direction.NORTH.name)     # Output: ‘NORTH’
print(Direction.NORTH.value)     # Output: 1

# Access by value
print(Direction(3))                        # Output: Direction.SOUTH

Iterating Through Enum Members

from enum import Enum
class Direction(Enum):
    NORTH = 1
    EAST = 2
    SOUTH = 3
    WEST = 4

for direction in Direction:
    print(direction.name, end=’ ’)


#Output: NORTH EAST SOUTH WEST

By defining enum, you’re fixing the list of values for enum class, in the above example direction can only be NORTH, EAST, WEST and SOUTH it cannot be any other values.
For e.g.
NORTH-EAST, 30 degrees to WEST
Cannot be a value of this enum as it is not mentioned in it.

Example: Imagine you are building a simple application to manage a weekly schedule. Using Enums can help you represent the days of the week in a clear and structured way.

from enum import Enum

class Day(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7

# Function to check if a day is a weekend
def is_weekend(day):
    if day in (Day.SATURDAY, Day.SUNDAY):
        return True
return False


today = Day.WEDNESDAY

print(f”Today is {today.name}.”) # Output: Today is WEDNESDAY.

# Check if today is a weekend
if is_weekend(today):
      print(“It’s the weekend!”)
else:
      print(“It’s a weekday.”)
#Output: It’s a weekday.

Course Video

Task:
1. Create an enum for traffic light signals. Assign them values like red=1, yellow=2 and green=3. Take input from the user which light is on and print the message like “stop” for red, “Get ready” for yellow and “Go…” for green respectively.

Task Video

YouTube Reference :