How to Create Enum Class in Python: Simple Guide
In Python, you create an enum class by importing
Enum from the enum module and defining a class that inherits from Enum. Inside the class, define members as class attributes with unique values.Syntax
To create an enum class, import Enum from the enum module. Then define a class that inherits from Enum. Inside the class, list enum members as attributes with assigned values.
- Import: Bring in
Enumfrom theenummodule. - Class definition: Create a class that inherits from
Enum. - Members: Define members as attributes with unique values.
python
from enum import Enum class Color(Enum): RED = 1 GREEN = 2 BLUE = 3
Example
This example shows how to create an enum class Day with days of the week as members. It also demonstrates how to access enum members and their values.
python
from enum import Enum class Day(Enum): MONDAY = 1 TUESDAY = 2 WEDNESDAY = 3 THURSDAY = 4 FRIDAY = 5 SATURDAY = 6 SUNDAY = 7 # Access enum member print(Day.MONDAY) # Access member name print(Day.MONDAY.name) # Access member value print(Day.MONDAY.value)
Output
Day.MONDAY
MONDAY
1
Common Pitfalls
Common mistakes when creating enum classes include:
- Not inheriting from
Enum, which means the class won't behave like an enum. - Using duplicate values for different members, which can cause unexpected behavior.
- Trying to change enum members after creation, which is not allowed.
Here is an example of a wrong and right way:
python
from enum import Enum # Wrong: No inheritance from Enum class WrongColor: RED = 1 GREEN = 2 # Right: Inherit from Enum class RightColor(Enum): RED = 1 GREEN = 2
Quick Reference
| Concept | Description |
|---|---|
| Enum import | from enum import Enum |
| Define enum class | class Name(Enum): |
| Add members | MEMBER = value |
| Access member | EnumClass.MEMBER |
| Get name | EnumClass.MEMBER.name |
| Get value | EnumClass.MEMBER.value |
Key Takeaways
Always inherit your class from Enum to create an enum class.
Define enum members as class attributes with unique values.
Access enum members using ClassName.MEMBER syntax.
Enum members are immutable and cannot be changed after creation.
Use the enum module from Python's standard library for enums.