How can I represent an 'Enum' in Python?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Enums (short for Enumerations) in Python are a way of organizing collections of related constants. They can enhance readability and maintainability of code by grouping similar values and providing a type-checking mechanism. An Enum class in Python is used to represent these constant values.
Basics of Enum in Python
Python provides the Enum class in the enum module, which was officially added in version 3.4. An Enum is a class type which inherits from the base Enum class.
Here's a simple example to define an Enum:
In this example, Color is an Enum with three members: RED, GREEN, and BLUE. Each member of an Enum is associated with a unique, constant value.
Accessing Enum Members
You can access enum members either by their name or by their value:
Attributes of Enum Members
Each member of an Enum has two important attributes:
name: the name of the member (as a string)value: the value assigned to the member
Iteration and Length
Enums are iterable and their length can be determined:
Comparing Enums
Enum members are singletons, and identity checks (using is) can be used for comparison, besides the usual equality checks (==):
Unique Enums
To ensure all enum values are unique, Python provides the @unique decorator:
Auto-numbering
If you don't care about the values of the Enum members and just need unique constants, you can use auto() function for automatic value assignments:
This function will automatically assign each member a unique integer value.
Summary Table
Here’s a succinct table to summarize the key concepts of using Enums in Python:
| Feature | Description |
| Definition | Class type inheriting from Enum, with named members and values |
| Accessing Members | By name (e.g., Color.RED) or by value (e.g., Color(1)) |
| Attributes | name and value of Enum members |
| Iterability and Length | Can loop through the Enum members with a for loop, len(Enum) |
| Unique Values | Ensured using @unique decorator |
| Auto-numbering | Automatic unique value assignment using auto() function |
Use Cases for Enums
Enums are particularly useful when dealing with a set of predefined options, like states, modes, or configurations. Using Enums can make your code more readable and less error-prone, since Enums enforce values to be one of the predefined constants.
In conclusion, Enums in Python offer streamlined syntax and powerful features that ensure your code can handle predefined sets of constants in a clean and efficient manner. Whether you're handling application states, response statuses, or other categorical data, Enums can be a valuable addition to your Python coding toolkit.

