Sub topic 11
Common pitfalls and how to avoid them
This chapter assumes you can define an Enum, read .name and .value, and tell == from is. It also assumes you know what IntEnum and StrEnum are. The mistakes below are the ones that most often surprise people after the basics.
Pitfall 1: Comparing a member to its raw value
A plain Enum member is not equal to its value. This is a common bug when data comes from JSON or a database.
from enum import Enum
class Color(Enum):
RED = 1
print(Color.RED == 1) # False
print(Color.RED.value == 1) # True
print(Color(1) is Color.RED) # TrueConvert the raw value to a member at the boundary with Color(raw). Then compare members with is or == everywhere else.
Pitfall 2: Assuming a member is falsy when its value is 0
Members of a plain Enum are always truthy, whatever their value.
from enum import Enum, IntEnum
class Plain(Enum):
NONE = 0
class Num(IntEnum):
NONE = 0
print(bool(Plain.NONE)) # True
print(bool(Num.NONE)) # FalseDo not write if status: to test for a "zero" member. Compare explicitly with status is Plain.NONE.
Pitfall 3: Expecting IntEnum to keep types apart
IntEnum members are real integers. Members of two unrelated enums can therefore compare equal.
from enum import IntEnum
class Size(IntEnum):
SMALL = 1
class Priority(IntEnum):
LOW = 1
print(Size.SMALL == Priority.LOW) # True
print(Size.SMALL + 1) # 2If you want type safety, use a plain Enum. Use IntEnum only when the members must work as numbers, for example when you pass them to a library that expects integers.
Pitfall 4: Forgetting that failed lookups raise
Color(5) raises ValueError, and Color["PINK"] raises KeyError. Catch the right exception for each form.
from enum import Enum
class Color(Enum):
RED = 1
def parse(raw):
try:
return Color(raw)
except ValueError:
return None
print(parse(1)) # Color.RED
print(parse(5)) # NonePitfall 5: Losing aliases when you iterate
Iteration skips aliases, so a loop over the class can hide names that exist. Use __members__ when you need every name. Add @unique if duplicates would be a bug, as when you define status codes by hand.
Pitfall 6: Defining things that do not become members
Functions and descriptors in the class body become methods, not members. Names that start and end with double underscores are also skipped. Assigning a lambda to a name therefore creates a method.
from enum import Enum
class Op(Enum):
ADD = 1
helper = lambda self: "I am a method"
print(list(Op)) # [<Op.ADD: 1>]
print(Op.ADD.helper()) # I am a methodPitfall 7: Trying to change or extend an enum
Members are constants. Reassigning one raises AttributeError. An enum that already has members cannot be subclassed, and trying raises TypeError.
from enum import Enum
class Color(Enum):
RED = 1
try:
Color.RED = 2
except AttributeError as exc:
print("reassign failed:", exc)
try:
class MoreColor(Color):
BLUE = 2
except TypeError as exc:
print("extend failed:", exc)If you need shared behavior, put it in a base class that has methods but no members. Then subclass that base.
Quick reference
| Symptom | Likely cause | Fix |
|---|---|---|
| `Color.RED == 1` is `False` | Plain `Enum` does not equal its value | Compare members, or use `.value` |
| `if member:` always passes | Plain `Enum` members are truthy | Compare explicitly |
| Two enums compare equal | Both are `IntEnum` with the same number | Use plain `Enum` |
| A name is missing from a loop | It is an alias | Use `__members__` or `@unique` |
| A name is not a member | Its value is a function | Move it out of the member list |
Exercise
Given class Level(IntEnum): OFF = 0; ON = 1, what do bool(Level.OFF) and Level.ON == True print, and why would a plain Enum behave differently?
Show answer
Both print True for the second and False for the first: bool(Level.OFF) is False and Level.ON == True is True. IntEnum members are ints, so they follow int truthiness and equality (True == 1). A plain Enum would make bool(Level.OFF) True and Level.ON == True False, because members are always truthy and never equal raw values.