25

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?

0

1 Answer 1

38

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

2
  • 1
    Do we require unique if we are using auto? Jun 8, 2022 at 9:39
  • 2
    "require"... no, but it doesn't hurt. @unique might still be a good idea if you want to help future 'you' or whoever touches the code next, to be sure the values are all unique. Incase some future edit of the code doesn't use auto, or some other obscure reason causes a duplicate.
    – Michael
    Jun 16, 2022 at 2:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.