Python @unique Decorator Understanding

Python @unique Decorator Understanding

The main purpose of the @unique decorator in the ython enumeration (Enum) is: to check for duplicate values in the enumeration.

The following is an example.

from enum import Enum, unique
@unique
class UserStatus(Enum):
    active=1
    not_active=2
    na=1
print(UserStatus(1))

Let's run the result and see.

Traceback (most recent call last):
File "E:\Python\Python37\lib\code.py", line 90, in runcode
    exec(code, self.locals)
File "<input>", line 2, in 
File "E:\Python\Python37\lib\enum.py", line 869, in unique
    (enumeration, alias_details))
ValueError: duplicate values found in : na -> active

It is suspected that a duplicate error is seen.

This suspicious is used when the enumeration has more content to avoid duplicate content, and with this decorator, the values can be constrained.