15

I recently came across this code from a stackoverflow question:

@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 this code snippet?

Alec
  • 7,110
  • 7
  • 28
  • 53

1 Answers1

26

From the documentation:

[@unique is] a class decorator specifically for enumerations. It searches an enumeration’s members gathering any aliases it finds; if any are found ValueError is raised with the details

Basically, it raises an error 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
Alec
  • 7,110
  • 7
  • 28
  • 53