Sub topic 4
Forbidding duplicate values with @unique
This chapter assumes you have read the earlier chapters on defining an Enum, looking members up by name and value, and iterating over members and aliases. You should also be comfortable applying a decorator to a class and catching exceptions with try/except.
The problem: silent aliases
By default, an Enum accepts two names with the same value. The second name becomes an alias for the first member. Python raises no error and emits no warning.
from enum import Enum
class Status(Enum):
ACTIVE = 1
ENABLED = 1 # alias of ACTIVE
DISABLED = 2
print(Status.ENABLED is Status.ACTIVE) # True
print(list(Status)) # [<Status.ACTIVE: 1>, <Status.DISABLED: 2>]Sometimes this is what you want. Often it is a copy-paste mistake. Suppose you add PENDING = 2 to a long enum and don't notice that DISABLED already uses 2. Status.PENDING quietly becomes another name for Status.DISABLED. Code that checks status is Status.PENDING then also matches disabled records, and iteration no longer lists PENDING at all.
The @unique decorator turns that silent behavior into an immediate error.
Using @unique
unique lives in the enum module. You apply it directly above the class definition.
from enum import Enum, unique
try:
@unique
class Status(Enum):
ACTIVE = 1
ENABLED = 1
DISABLED = 2
except ValueError as exc:
print(exc)
# duplicate values found in <enum 'Status'>: ENABLED -> ACTIVEThe message names every alias and the member it points to, in the form alias -> canonical member. The canonical member is the one defined first, because Python creates a member for the first name that uses a value.
When the class has no duplicates, @unique does nothing visible and returns the class unchanged.
from enum import Enum, auto, unique
@unique
class Direction(Enum):
NORTH = auto()
EAST = auto()
SOUTH = auto()
WEST = auto()
print(Direction.SOUTH.value) # 3Several duplicates are reported together
The decorator collects all aliases before it raises, so you can fix them in one pass. Each alias is listed with its target, separated by commas.
from enum import Enum, unique
try:
@unique
class Shade(Enum):
DARK = 1
BLACK = 1
LIGHT = 2
WHITE = 2
GREY = 3
except ValueError as exc:
print(exc)
# duplicate values found in <enum 'Shade'>: BLACK -> DARK, WHITE -> LIGHTHow it works internally
@unique does not hook into class creation. The Enum metaclass builds the whole class first, and aliases are already in place when the decorator runs. The decorator then inspects the finished class.
The check is roughly equivalent to this code:
def find_aliases(enumeration):
duplicates = []
for name, member in enumeration.__members__.items():
if name != member.name:
duplicates.append((name, member.name))
return duplicates__members__ is a read-only mapping that includes aliases. For a real member, the key and member.name are identical. For an alias, the key is the alias name, but the member object is the original, so member.name is the canonical name. A mismatch identifies an alias. If any pair is found, the decorator builds the message and raises ValueError.
Two consequences follow from this design.
- The class name is never bound on failure. The decorator raises before the assignment of the decorated class to its name, so
Statusstays undefined (or keeps an older definition) after the error. In a module, the import fails, which is usually the point. - The error appears at import time. A duplicate is caught as soon as the module loads. You do not need a test that exercises the specific code path.
Equality, not identity, defines "duplicate"
Python decides that two values are the same using the same lookup rules as Status(1). Values that compare equal and hash equal count as duplicates. This produces some surprises with numbers.
from enum import Enum, unique
try:
@unique
class Flagish(Enum):
ONE = 1
YES = True # True == 1 and hash(True) == hash(1)
ONE_F = 1.0 # 1.0 == 1 as well
except ValueError as exc:
print(exc)
# duplicate values found in <enum 'Flagish'>: YES -> ONE, ONE_F -> ONEStrings are compared exactly, so "low" and "LOW" are different values and do not trigger @unique. If you want case-insensitive uniqueness, you must normalize the values yourself.
Unhashable values, such as lists, also work. Enum falls back to a linear equality search for them, and @unique still detects aliases because it compares names, not hashes.
from enum import Enum, unique
try:
@unique
class Pair(Enum):
A = [1, 2]
B = [1, 2]
except ValueError as exc:
print(exc)
# duplicate values found in <enum 'Pair'>: B -> Aauto() and the duplicate trap
auto() removes most accidental duplicates, because it generates a new value each time. The danger appears when you mix auto() with explicit values. By default, auto() picks the last value assigned so far plus one, and it does not look ahead to later explicit values.
from enum import Enum, auto, unique
try:
@unique
class Step(Enum):
FIRST = 1
SECOND = auto() # 2
THIRD = 2 # collides with SECOND
except ValueError as exc:
print(exc)
# duplicate values found in <enum 'Step'>: THIRD -> SECONDWithout @unique, Step.THIRD would silently be Step.SECOND. This is a good argument for either using auto() for every member or using explicit values for every member.
When aliases are intentional
Aliases are a legitimate tool, and @unique is the wrong choice when you rely on them. Two common reasons to keep them:
- Renaming without breaking callers. You rename
ENABLEDtoACTIVEand keep the old name as an alias for a deprecation period. - Several spellings for one concept. For example,
Color.GREYandColor.GRAY.
In those cases, leave off @unique. Document each alias with a comment so a later reader knows the duplicate is deliberate.
| Situation | Use `@unique`? | Reason |
|---|---|---|
| Values are database codes or wire-protocol numbers | Yes | Two names for one code is almost always a typo |
| Members all use `auto()` | Optional | Duplicates cannot occur, but the decorator documents intent |
| Mixed `auto()` and explicit values | Yes | Explicit values can collide with generated ones |
| Backward-compatible renames | No | The alias is the feature |
| Synonyms such as `GREY` and `GRAY` | No | Same reason |
Choosing a default
Many teams apply @unique to every enum and remove it only when they add an intentional alias. The cost is one line per class. The benefit is that a mistake in a long list of values fails at import instead of causing a wrong branch at runtime. A matching style rule is useful: if a class has no @unique, a comment should say why.
Another option: enum.verify
Python 3.11 added enum.verify, a more general decorator that runs named checks. Its UNIQUE check does the same job as @unique and shares its limits. It also offers CONTINUOUS and NAMED_FLAGS for other constraints.
from enum import Enum, verify, UNIQUE
@verify(UNIQUE)
class Level(Enum):
LOW = 1
HIGH = 2
print(list(Level)) # [<Level.LOW: 1>, <Level.HIGH: 2>]verify requires Python 3.11 or later. @unique works on every version that has enum, so prefer it if your code must run on older interpreters.
Testing for duplicates
Because @unique raises at definition time, testing it means defining a class inside the test. The pattern below keeps the failing definition inside a function so the module still imports.
from enum import Enum, unique
def make_bad_enum():
@unique
class Bad(Enum):
X = 1
Y = 1
return Bad
def test_duplicates_are_rejected():
try:
make_bad_enum()
except ValueError as exc:
assert "duplicate values found" in str(exc)
assert "Y -> X" in str(exc)
else:
raise AssertionError("expected ValueError")
test_duplicates_are_rejected()
print("ok") # okYou rarely need to test @unique itself. A test that merely imports the module already fails if someone adds a duplicate.
Common mistakes
- Putting
@uniqueon the wrong line. The decorator goes directly aboveclass, not above an assignment or inside the class body. - Expecting it to run on instances. It checks the class definition only. Members are fixed after creation, so nothing else can add a duplicate later.
- Assuming it checks names. Repeating a member name in a class body already raises
TypeError("Attempted to reuse key") without@unique. The decorator addresses repeated values. - Forgetting numeric equality.
1,Trueand1.0collide, as shown above. - Using it on a deliberately aliased enum. The class then fails to import. Remove the decorator or remove the alias.
Exercise
Given the class below, what happens at import time, and which line would you change so Level.URGENT is a distinct member?
from enum import Enum, auto, unique
@unique
class Level(Enum):
LOW = auto()
MEDIUM = auto()
HIGH = 2
URGENT = auto()
Show answer
The @unique check raises ValueError saying "duplicate values found in <enum 'Level'>: HIGH -> MEDIUM". The reason is that auto() gives LOW the value 1 and MEDIUM the value 2, so the explicit HIGH = 2 repeats MEDIUM's value and becomes an alias. (URGENT would be 3, because auto() continues from the last value.) The fix is to change HIGH = 2 to HIGH = auto(), or to give every member an explicit, distinct value. URGENT is already distinct, so no change to that line is needed.
Exercise
Why does this class raise ValueError under @unique, even though the values look different? @unique class Mode(Enum): OFF = 0 DISABLED = False ON = 1
Show answer
Python treats values as equal when they compare equal and hash equally. False == 0, so DISABLED is an alias of OFF. The decorator reports "DISABLED -> OFF". To keep them separate, use values that are not equal, such as strings ("off", "disabled") or distinct integers.
Exercise
Write a short function that returns a dict mapping each alias name to its canonical member name for any enum class, using _members_. Return an empty dict if the enum has no aliases.
Show answer
def aliasmap(enumcls):
return {
name: member.name
for name, member in enumcls.members.items()
if name != member.name
}
For Status from the start of the chapter (ACTIVE = 1, ENABLED = 1, DISABLED = 2), aliasmap(Status) returns {'ENABLED': 'ACTIVE'}. This is the same comparison @unique performs: a name that differs from its member's own name is an alias.