enum.Enum, enum.auto, enum.unique
class enum.Enum
enum.auto()
@enum.uniqueDefine members, look them up by value or name, and reject duplicated values with unique.
| Parameter | Description |
|---|---|
value / name | Color(1) returns the member whose value is 1. Color['RED'] returns the member whose name is RED. |
Returns: The class call and the name index return a member. auto is replaced by a generated value when the class is created.
Raises
TypeError— Raised by ordered comparisons between plain Enum members, such as Color.RED < Color.BLUE on Python 3.13.12.ValueError— @unique raises ValueError when two names would share one value. Color(missing) also raises ValueError.KeyError— Color['missing'] raises KeyError when the name does not exist.
- Color.RED == Other.RED is False even though both values are 1, because they belong to different Enum classes and are not integers.
from enum import Enum, auto, unique
class Color(Enum):
RED = 1
BLUE = 2
class Other(Enum):
RED = 1
print(Color.RED == Color.RED, Color.RED is Color.RED, Color.RED == 1)
print(Color.RED == Color.BLUE, Color.RED == Other.RED)
print(Color(1) is Color.RED, Color["RED"] is Color.RED)
print(Color.RED.name, Color.RED.value)
try:
Color.RED < Color.BLUE
except TypeError as err:
print(type(err).__name__)
try:
@unique
class Dup(Enum):
A = 1
B = 1
except ValueError as err:
print(type(err).__name__)
class AutoC(Enum):
A = auto()
B = auto()
print(AutoC.A.value, AutoC.B.value)Expected output
True True False
False False
True True
RED 1
TypeError
ValueError
1 2