Sub topic 11
Common pitfalls and how to avoid them
This chapter assumes you can define an Enum, read .name and .value, and look members up by value or name. It also assumes you know Enum, IntEnum, StrEnum, Flag and auto(), and the difference between == and is. Most enum bugs come from a few surprises that follow from how the module works. The sections below cover each one, with a fix.
Comparing a member to a raw value
A plain Enum member is an object of its own class. It is never equal to the value it wraps.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
print(Color.RED == 1) # False
print(Color.RED.value == 1) # True
print(Color(1) is Color.RED) # TrueThis bites when data arrives from a database, a config file or an API as an int or str. Convert the raw value to a member once, at the boundary, and compare members after that. Do not scatter .value comparisons through the code.
Plain Enum members are singletons, so is is the idiomatic comparison. == also works, because the default equality for an Enum is identity.
Failed lookups raise different errors
Lookup by value and lookup by name fail with different exceptions.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
def parse_color(raw):
try:
return Color(raw)
except ValueError:
return None
print(parse_color(2)) # Color.GREEN
print(parse_color(9)) # None
try:
Color["PINK"]
except KeyError as exc:
print("KeyError", exc) # KeyError 'PINK'Color(9) raises ValueError. Color["PINK"] raises KeyError. Attribute access such as Color.PINK raises AttributeError. Catch the one that matches the lookup you use. If you want one fallback for bad input, implement _missing_ (covered in the last chapter) or wrap the lookup in a helper like parse_color.
Accidental aliases
If two names share a value, the second becomes an alias of the first. No error is raised. A typo in a value can therefore remove a member from iteration without any warning.
from enum import Enum, unique
class Level(Enum):
LOW = 1
MEDIUM = 2
HIGH = 2 # typo, meant 3
print(list(Level)) # [<Level.LOW: 1>, <Level.MEDIUM: 2>]
print(Level.HIGH) # Level.MEDIUMHIGH still exists as a name, but for level in Level never yields it. Decorate enums with @unique unless you really want aliases. The decorator turns the typo into an error at import time:
from enum import Enum, unique
try:
@unique
class Level(Enum):
LOW = 1
MEDIUM = 2
HIGH = 2
except ValueError as exc:
print(exc) # duplicate values found in <enum 'Level'>: HIGH -> MEDIUMWhen you do want aliases, for example to keep an old name working, say so in a comment. To list every name including aliases, use __members__.
The trailing comma
A trailing comma makes the value a tuple. This is plain Python tuple syntax, and enum bodies do not special-case it.
from enum import Enum
class Port(Enum):
HTTP = 80,
HTTPS = 443
print(Port.HTTP.value) # (80,)
print(Port.HTTPS.value) # 443If lookups such as Port(80) fail even though HTTP = 80 appears to be defined, look for a stray comma.
Truthiness and ordering
Every member of a plain Enum is truthy, even when its value is 0 or "". Members that mix in a type follow that type's rules instead. Plain Enum members also do not support < or >.
from enum import Enum, IntEnum
class Switch(Enum):
OFF = 0
ON = 1
class Gear(IntEnum):
NEUTRAL = 0
FIRST = 1
print(bool(Switch.OFF)) # True
print(bool(Gear.NEUTRAL)) # False
print(Gear.NEUTRAL < Gear.FIRST) # True
try:
Switch.OFF < Switch.ON
except TypeError as exc:
print(exc) # '<' not supported between instances of 'Switch' and 'Switch'Do not write if mode: to test whether a plain Enum member is "off". Compare with is Switch.OFF. If members have a real order, use IntEnum, or define __lt__ yourself or compare .value. Do not rely on definition order.
IntEnum equals any int, including other enums
IntEnum members are integers. That makes them equal to plain integers and to members of any other IntEnum with the same number.
from enum import IntEnum
class Color(IntEnum):
RED = 1
class Shape(IntEnum):
CIRCLE = 1
print(Color.RED == Shape.CIRCLE) # True
print(Color.RED == 1) # True
print({1: "one"}[Color.RED]) # oneThis loses the type safety that makes enums useful. A function that expects a Shape happily accepts a Color at runtime. It also lets members leak into arithmetic: Color.RED + 1 is the plain integer 2.
Choose IntEnum only when you must interoperate with code that needs integers, such as protocol constants or C libraries. For everything else, use Enum.
String conversion differs by type and version
The text you get from str() and from f-strings depends on the enum's base classes and on the Python version.
| Enum kind | `str(member)` | Notes |
|---|---|---|
| `Enum` | `Color.RED` | Same in f-strings. |
| `IntEnum` | `1` on 3.11+ | Before 3.11, `str()` returned `Priority.LOW`. |
| `StrEnum` | the string value | Needs 3.11+. |
| `class X(str, Enum)` | version dependent | Older versions format as the value, 3.12+ as `X.NAME`. |
If you write messages or build file names, do not interpolate a member and hope. Use member.value or member.name, whichever you mean. On 3.11+, prefer StrEnum over class X(str, Enum) when you want string behavior.
JSON and other serializers
The json module cannot serialize a plain Enum member. Convert it yourself, or use a mixin type.
import json
from enum import Enum, StrEnum # StrEnum requires Python 3.11+
class Color(Enum):
RED = "red"
class Mode(StrEnum):
READ = "r"
try:
json.dumps({"color": Color.RED})
except TypeError as exc:
print(exc) # Object of type Color is not JSON serializable
print(json.dumps({"color": Color.RED.value})) # {"color": "red"}
print(json.dumps({"mode": Mode.READ})) # {"mode": "r"}Reading JSON back is the reverse: call Color("red") on the decoded string. Keep both directions in one place, such as a from_json and to_json pair, so the stored form never changes by accident. Store .value, not .name, if names may be renamed later. Or store names and treat renaming as a breaking change.
Members are fixed
Once the class body finishes, members cannot be reassigned, and a class that has members cannot be subclassed.
from enum import Enum
class Color(Enum):
RED = 1
try:
Color.RED = 2
except AttributeError:
print("cannot reassign a member")
try:
class MoreColors(Color):
BLUE = 2
except TypeError:
print("cannot subclass an enum with members")An enum with no members can be subclassed, and this is how you share methods across several enums:
from enum import Enum
class Labeled(Enum):
def label(self):
return self.name.replace("_", " ").title()
class Unit(Labeled):
SQUARE_METER = 1
print(Unit.SQUARE_METER.label()) # Square MeterWhat counts as a member
Not every assignment in an enum body creates a member.
- Functions, including
lambdaassignments, and descriptors such aspropertybecome ordinary class attributes, not members. - Names that begin and end with double underscores are left alone.
- Names with a single leading underscore, such as
_ignore_and_missing_, are reserved for the enum machinery. Avoid inventing your own. - Anything else, including a list, a dict or a tuple, becomes a member whose value is that object.
An enum whose value is a function is a common surprise. If you want to store a callable as a member value, wrap it in a tuple or use functools.partial, which is not a descriptor. A plain def in the body is a method.
Membership tests with `in`
The result of x in Color depends on the Python version. On 3.12 and later, 1 in Color is True if some member has that value. On older versions, testing a non-member with in raises TypeError. Code that must run on both should avoid the test and use a helper like parse_color above, or compare against {m.value for m in Color}.
Quick reference
| Symptom | Likely cause | Fix |
|---|---|---|
| `Color.RED == 1` is `False` | Plain `Enum` is not its value | Convert with `Color(1)` or use `.value` |
| A member is missing from `list(Color)` | Duplicate value created an alias | Add `@unique` |
| `.value` is `(80,)` | Trailing comma in definition | Remove the comma |
| `if member:` is always true | Plain `Enum` members are truthy | Compare with `is` |
| `TypeError` on `<` | Plain `Enum` has no ordering | Use `IntEnum` or compare values |
| Different enums compare equal | Both are `IntEnum` | Use `Enum` unless you need ints |
| `json.dumps` fails | Plain `Enum` is not serializable | Store `.value` or use `StrEnum` |
Exercise
A teammate writes class Role(Enum): ADMIN = "admin"; STAFF = "admin" by mistake, then loops over Role to build a dropdown. What does the dropdown contain, why, and which two changes would catch the mistake?
Show answer
The dropdown contains only ADMIN. STAFF has the same value as ADMIN, so it becomes an alias, and iteration skips aliases. Decorating the class with @unique would raise ValueError at import time. Checking list(Role.__members__) against list(Role) in a test would also reveal the hidden alias.
Exercise
An API returns {"priority": 2}. You have class Priority(Enum): LOW = 1; HIGH = 2. Write the code that converts it safely into a member and returns None when the value is unknown, then say which exception you catch and why a plain == against 2 would not work.
Show answer
Use try: return Priority(data["priority"]) with except ValueError: return None. Lookup by value raises ValueError when no member has that value. Comparing Priority.HIGH == 2 returns False because a plain Enum member is not equal to its raw value.