Python Enum Gotcha

There is plenty of useful information in Why You Should Use More Enums In Python – A gentle introduction to enumerations in Python. After reading it I decided to look into using Enums more. Unfortunately I hit a major Gotcha quite quickly.

Basically, comparisons don’t work with vanilla Enum (unlike IntEnum). Checking the official Python documentation seemed to confirm this understanding:

“Comparisons against non-enumeration values will always compare not equal (again, IntEnum was explicitly designed to behave differently …)” — https://docs.python.org/3/library/enum.html

In the snippet below, Pieces is subclasses vanilla Enum and has, at least from my point of view, very unexpected results. Pieces2 is based on IntEnum and behaves as might be expected.

import enum

class Pieces(enum.Enum):
    PAWN = 8
    ROOK = 2
    BISHOP = 2


print(2 == Pieces.ROOK) ## False WAT?! Always not equal to non enums
print(Pieces.ROOK == 2) ## False WAT?!
print(Pieces.BISHOP == Pieces.ROOK) ## True
print(Pieces.PAWN == Pieces.ROOK) ## False


class Pieces2(enum.IntEnum):
    PAWN = 8
    ROOK = 2
    BISHOP = 2


print(2 == Pieces2.ROOK) ## True
print(Pieces2.ROOK == 2) ## True
print(Pieces2.BISHOP == Pieces2.ROOK) ## True
print(Pieces2.PAWN == Pieces2.ROOK) ## False

It is easy to imagine this behaviour creating baffling bugs. Interesting.

Leave a Reply