What is Enum in Python: Simple Explanation and Usage
enum (short for enumeration) is a special class that defines a set of named constant values. It helps group related values under meaningful names, making code easier to read and maintain.How It Works
Think of an enum like a box of labeled jars, where each jar holds a fixed value. Instead of using random numbers or strings scattered in your code, you use these labeled jars to clearly show what each value means. This makes your code less confusing and less error-prone.
In Python, you create an enum by defining a class that inherits from the built-in Enum class. Each item inside this class is a constant with a name and a value. Once set, these values do not change, which helps prevent mistakes like using wrong or inconsistent values.
Example
This example shows how to create an enum for days of the week and how to use it in a program.
from enum import Enum class Day(Enum): MONDAY = 1 TUESDAY = 2 WEDNESDAY = 3 THURSDAY = 4 FRIDAY = 5 SATURDAY = 6 SUNDAY = 7 # Using the enum print(Day.MONDAY) # Prints the enum member print(Day.MONDAY.name) # Prints the name 'MONDAY' print(Day.MONDAY.value) # Prints the value 1 # Comparing enum members if Day.MONDAY == Day.TUESDAY: print("Same day") else: print("Different days")
When to Use
Use enums when you have a fixed set of related values that should not change, like days of the week, directions (North, South, East, West), or status codes (Success, Error, Pending). Enums make your code clearer by replacing magic numbers or strings with meaningful names.
For example, if you write a program that handles traffic lights, using an enum for the light colors helps avoid mistakes and makes the code easier to understand and maintain.
Key Points
- An
enumgroups related constant values with names. - It improves code readability and reduces errors.
- Enum members have a
nameand avalue. - Once defined, enum values should not change.
- Use enums for fixed sets like days, states, or categories.