What does the @unique decorator do in python?
Question:
I recently came across this code:
@unique
class NetlistKind(IntEnum):
Unknown = 0
LatticeNetlist = 1
QuartusNetlist = 2
XSTNetlist = 4
CoreGenNetlist = 8
All = 15
What does the @unique
decorator do, and what is its purpose in the above snippet?
Answers:
Summary
unique
is a class decorator for Enum
that raises a ValueError if there are any duplicate enumeration values.
This code
from enum import unique, Enum
@unique
class Mistake(Enum):
ONE = 1
TWO = 2
THREE = 3
FOUR = 3
Produces this error:
ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE
More Details
From the documentation:
Context
By default, enumerations allow multiple names as aliases for the same value. When this behavior isn’t desired, [unique] can be used to ensure each value is used only once in the enumeration
Description
[unique is] a class decorator specifically for enumerations. It ensures only one name is bound to any one value [in an enum]. [unique] searches an enumeration’s __members__
gathering any aliases it finds; if any are found ValueError is raised with the details
I recently came across this code:
@unique
class NetlistKind(IntEnum):
Unknown = 0
LatticeNetlist = 1
QuartusNetlist = 2
XSTNetlist = 4
CoreGenNetlist = 8
All = 15
What does the @unique
decorator do, and what is its purpose in the above snippet?
Summary
unique
is a class decorator for Enum
that raises a ValueError if there are any duplicate enumeration values.
This code
from enum import unique, Enum
@unique
class Mistake(Enum):
ONE = 1
TWO = 2
THREE = 3
FOUR = 3
Produces this error:
ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE
More Details
From the documentation:
Context
By default, enumerations allow multiple names as aliases for the same value. When this behavior isn’t desired, [unique] can be used to ensure each value is used only once in the enumeration
Description
[unique is] a class decorator specifically for enumerations. It ensures only one name is bound to any one value [in an enum]. [unique] searches an enumeration’s
__members__
gathering any aliases it finds; if any are found ValueError is raised with the details