Saturday, 11 September 2021

Python: Ensure unique enum values

Sometimes, you want to maintain the uniqueness in enum member values. You can achieve this behaviour using the class decorator @enum.unique.

 

uniqueDecorator.py

from enum import Enum, unique

@unique
class Day(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 6

for day in Day:
    print(day)

 

Output

ValueError: duplicate values found in <enum 'Day'>: SUNDAY -> SATURDAY

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment