enum in Python
Enums in Python are used to define a set of named constant values. They make code cleaner, more readable and prevent using invalid values. Each member of an Enum has a name and a value
- Enums can be easily accessed, compared, or used in loops and dictionaries.
- Help in assigning meaningful names to integer values to improve code readability and maintainability.
- Mainly useful when we have a small set of possible values for an item like directions, days of week, etc.
Enums are created by defining a class that inherits from the Enum class. Each attribute inside the class represents a unique, named constant with a specific value. These members can be easily accessed using their name or value.
from enum import Enum
class Season(Enum):
SPRING = 1
SUMMER = 2
AUTUMN = 3
WINTER = 4
print(Season.SUMMER)
print(Season.SUMMER.name)
print(Season.SUMMER.value)
Output
Season.SUMMER SUMMER 2
Explanation:
- Season['AUTUMN'].value: Access by name.
- Season(2).name: Access by value.
- Enum values are unique and immutable.
Iterating Over Enum Members
You can use a for loop to go through all Enum members and access each member’s name and value, making it easy to display or process them.
from enum import Enum
class Week(Enum):
SUNDAY = 1
MONDAY = 2
TUESDAY = 3
WEDNESDAY = 4
for s in Week:
print(s.value, "-", s)
Output
1 - Week.SUNDAY 2 - Week.MONDAY 3 - Week.TUESDAY 4 - Week.WEDNESDAY
Enums are Hashable (Can Be Used in Dictionaries)
Enums are hashable, meaning they can be used as keys in dictionaries or elements in sets, useful for mapping Enum members to specific values or actions.
from enum import Enum
class Animal(Enum):
DOG = 1
CAT = 2
LION = 3
sounds = {
Animal.DOG: "bark",
Animal.LION: "roar"
}
print(sounds[Animal.DOG])
Output
bark
Explanation:
- Enum members are hashable, so they can serve as dictionary keys.
- sounds[Animal.DOG]: retrieves the value associated with Animal.DOG.
Comparing Enum Members
Enums support both identity (is) and equality (==) comparisons. The is operator checks if two members are the exact same object, while == checks if their values are equal.
from enum import Enum
class Fruit(Enum):
APPLE = 1
BANANA = 2
ORANGE = 3
print(Fruit.APPLE is Fruit.BANANA)
print(Fruit.ORANGE == Fruit.BANANA)
Output
False False
Advantages of Enum
- Makes code clearer and more readable.
- Helps group related constants in one place.
- Provides type safety prevents using invalid values.
- Easy to iterate and compare.
- Hashable: can be used as keys in dictionaries or elements in sets.