Sub topic 4
Forbidding duplicate values with @unique
This chapter assumes you know how to define an Enum, how iteration skips aliases, and how decorators wrap a class. If aliases are new to you, review the previous chapter first.
Why duplicates are risky
When two names in an Enum share a value, Python does not raise an error. The second name becomes an alias for the first member. That is sometimes intended, but often it is a copy-paste mistake that goes unnoticed.
from enum import Enum
class Status(Enum):
ACTIVE = 1
DISABLED = 2
SUSPENDED = 2 # meant to be 3
print(Status.SUSPENDED) # Status.DISABLED
print(list(Status)) # [<Status.ACTIVE: 1>, <Status.DISABLED: 2>]Status.SUSPENDED is the same object as Status.DISABLED. Code that checks for SUSPENDED will treat disabled accounts as suspended, and nothing warns you. Iteration also skips the alias, so a loop that builds a menu will show only two options.
Applying @unique
The unique decorator from the enum module checks the finished class and raises ValueError if any name is an alias.
from enum import Enum, unique
try:
@unique
class Status(Enum):
ACTIVE = 1
DISABLED = 2
SUSPENDED = 2
except ValueError as error:
print(error)The output is:
duplicate values found in <enum 'Status'>: SUSPENDED -> DISABLEDThe message lists each alias and the member it points to, so you can find the bad line quickly. A correct class passes silently and is returned unchanged:
from enum import Enum, unique
@unique
class Status(Enum):
ACTIVE = 1
DISABLED = 2
SUSPENDED = 3
print(len(Status)) # 3How the check works
@unique is a class decorator. Python first builds the whole enum class, with aliases already resolved. The decorator then walks __members__, which includes aliases, and reports every entry whose name differs from the name of the member it points to.
The diagram below shows the sequence.
The error is raised when the module is imported, not when a member is first used. A typo is therefore caught at startup or in your first test run.
What @unique does not catch
The check compares values using the same rules the enum uses to detect aliases, so it only reports names that would have become aliases. Two points are worth knowing:
- It does not stop you from mixing
auto()and manual values carelessly. If you writeA = auto()and thenB = 1, both resolve to1and@uniquewill reject the class. That is the behavior you want, but the error appears at definition time. - It does not apply to values that are merely similar.
1and1.0compare equal, so they count as duplicates.1and"1"do not.
from enum import Enum, auto, unique
try:
@unique
class Level(Enum):
LOW = auto() # 1
HIGH = 1 # collides with LOW
except ValueError as error:
print(error)When to allow aliases
Do not apply @unique everywhere by reflex. Aliases are useful when you rename a member and want the old name to keep working, or when two names genuinely mean the same thing.
from enum import Enum
class Shape(Enum):
SQUARE = 1
RECTANGLE_EQUAL_SIDES = 1 # deliberate aliasA good rule: use @unique when each name should be a distinct choice, such as states, commands or error codes. Leave it off when aliases are part of the design, and add a comment saying so.
Exercise
Exercise
The class below is decorated with @unique. Does it raise ValueError, and if so, what names does the message mention? from enum import Enum, auto, unique @unique class Step(Enum): FIRST = auto() SECOND = auto() THIRD = 2
Show answer
Yes. auto() gives FIRST the value 1 and SECOND the value 2. THIRD is also 2, so it would be an alias of SECOND. The message is "duplicate values found in <enum 'Step'>: THIRD -> SECOND".