Python
Enum
Programming
Coding
Python Tutorial

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:

python
1from enum import Enum
2
3class Color(Enum):
4    RED = 1
5    GREEN = 2
6    BLUE = 3

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:

python
1# Access by name
2print(Color.RED)  # Output: Color.RED
3
4# Access by value
5print(Color(1))   # Output: Color.RED

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
python
member = Color.RED
print(member.name)  # Output: 'RED'
print(member.value) # Output: 1

Iteration and Length

Enums are iterable and their length can be determined:

python
1for color in Color:
2    print(color)
3
4# Output:
5# Color.RED
6# Color.GREEN
7# Color.BLUE
8
9print(len(Color))  # Output: 3

Comparing Enums

Enum members are singletons, and identity checks (using is) can be used for comparison, besides the usual equality checks (==):

python
assert Color.RED is Color.RED  # True because both are the same instance
assert Color.RED == Color.RED  # Also True
assert Color.RED != Color.GREEN  # True because they are different instances

Unique Enums

To ensure all enum values are unique, Python provides the @unique decorator:

python
1from enum import Enum, unique
2
3@unique
4class UniqueColor(Enum):
5    RED = 1
6    GREEN = 2
7    BLUE = 3
8    # Uncommenting the following line will raise a ValueError
9    # PURPLE = 1

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:

python
1from enum import auto
2
3class AutoNumberColor(Enum):
4    RED = auto()
5    GREEN = auto()
6    BLUE = auto()

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:

FeatureDescription
DefinitionClass type inheriting from Enum, with named members and values
Accessing MembersBy name (e.g., Color.RED) or by value (e.g., Color(1))
Attributesname and value of Enum members
Iterability and LengthCan loop through the Enum members with a for loop, len(Enum)
Unique ValuesEnsured using @unique decorator
Auto-numberingAutomatic 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.


Course illustration
Course illustration

All Rights Reserved.