2 min read

Python Enum Module

The enum module defines four enumeration classes that can be used to define unique sets of names and values: Enum, IntEnum, Flag, and IntFlag. It also defines one decorator, unique, and one helper, auto.

Importing the Module

import enum

Creating an Enum

Enumerations are created using the class syntax, which makes them easy to read and write.

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

auto()

If the exact value is unimportant you can use auto().

from enum import Enum, auto

class Color(Enum):
    RED = auto()
    GREEN = auto()
    BLUE = auto()

Iteration

You can iterate over the members of an enumeration.

class Shape(Enum):
    SQUARE = 2
    DIAMOND = 4
    CIRCLE = 3

for shape in Shape:
    print(shape.name, shape.value)

Comparisons

Enum members are compared by identity.

if Shape.SQUARE is Shape.SQUARE:
    print("Identity comparison works")

IntEnum

IntEnum is the same as Enum, but its members are also integers and can be compared to integers.

from enum import IntEnum

class Shape(IntEnum):
    CIRCLE = 1
    SQUARE = 2

print(Shape.CIRCLE == 1) # True

Flag and IntFlag

Flag and IntFlag are used to define enumerations that can be combined using bitwise operators.

from enum import Flag, auto

class Color(Flag):
    RED = auto()
    GREEN = auto()
    BLUE = auto()
    WHITE = RED | GREEN | BLUE

print(Color.WHITE) # Color.WHITE
print(Color.RED in Color.WHITE) # True

The unique Decorator

By default, enumerations allow aliases (multiple names for the same value). To disallow this, use the @unique decorator.

from enum import Enum, unique

@unique
class Mistake(Enum):
    ONE = 1
    TWO = 2
    THREE = 3
    # FOUR = 3  # This would raise a ValueError

Programmatic Access

You can access members by name or value.

print(Color['RED'])  # Color.RED
print(Color(1))      # Color.RED (assuming RED=1)

programming/python/python