我最近遇到了这段代码:
@unique
class NetlistKind(IntEnum):
Unknown = 0
LatticeNetlist = 1
QuartusNetlist = 2
XSTNetlist = 4
CoreGenNetlist = 8
All = 15
@unique 装饰器的作用是什么?它在上述代码段中的用途是什么?
请您参考如下方法:
总结
unique 是 Enum 的类装饰器,如果有任何重复的枚举值,它会引发 ValueError。
这段代码
from enum import unique, Enum
@unique
class Mistake(Enum):
ONE = 1
TWO = 2
THREE = 3
FOUR = 3
产生这个错误:
ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE
更多详情
来自documentation :
上下文
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
描述
[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
