The enum.unique decorator in Python’s enum module ensures that all enumeration members have unique values. This is useful for catching errors where duplicate values might be assigned to different enumeration members.
Table of Contents
- Introduction
enum.uniqueFunction Syntax- Examples
- Basic Usage
- Detecting Duplicate Values
- Real-World Use Case
- Conclusion
Introduction
The enum.unique decorator is applied to an enumeration class to ensure that all its members have unique values. If duplicate values are detected, a ValueError is raised. This helps to prevent errors and maintain the integrity of the enumeration.
enum.unique Function Syntax
Here is how you use the enum.unique decorator:
from enum import Enum, unique
@unique
class EnumName(Enum):
MEMBER1 = value1
MEMBER2 = value2
MEMBER3 = value3
Parameters:
EnumName: The name of the enumeration.MEMBER: The symbolic name of the enumeration member.value: The constant value associated with the enumeration member.
Examples
Basic Usage
Define an enumeration with unique values using enum.unique.
Example
from enum import Enum, unique
@unique
class Day(Enum):
SUNDAY = 1
MONDAY = 2
TUESDAY = 3
WEDNESDAY = 4
THURSDAY = 5
FRIDAY = 6
SATURDAY = 7
print(Day.MONDAY)
print(Day.MONDAY.name)
print(Day.MONDAY.value)
Output:
Day.MONDAY
MONDAY
2
Detecting Duplicate Values
Attempt to define an enumeration with duplicate values to see the error raised by enum.unique.
Example
from enum import Enum, unique
try:
@unique
class Status(Enum):
ACTIVE = 1
INACTIVE = 0
PENDING = 1 # Duplicate value
except ValueError as e:
print(f"ValueError: {e}")
Output:
ValueError: duplicate values found in <enum 'Status'>: PENDING -> ACTIVE
Real-World Use Case
Ensuring Unique Error Codes
Use enum.unique to ensure that error codes in an application are unique.
Example
from enum import Enum, unique
@unique
class ErrorCode(Enum):
SUCCESS = 0
NOT_FOUND = 1
PERMISSION_DENIED = 2
UNKNOWN_ERROR = 99
print(ErrorCode.SUCCESS)
print(ErrorCode.PERMISSION_DENIED)
Output:
ErrorCode.SUCCESS
ErrorCode.PERMISSION_DENIED
Conclusion
The enum.unique decorator is used for ensuring that all members of an enumeration have unique values in Python. It helps catch errors early in the development process by raising a ValueError when duplicate values are detected. This can enhance the reliability and maintainability of your code by preventing accidental value duplication in enumerations.