Sub topic 9
IntEnum and StrEnum: enums that behave like int and str
This chapter assumes you can define a plain Enum, read .name and .value, and tell == from is. It builds on those ideas to show enums whose members also act as ordinary integers or strings.
Why a plain Enum is not enough
A plain Enum member is never equal to its raw value. That is usually what you want, because it stops Color.RED from being confused with the number 1. It becomes a nuisance when your enum must talk to code that expects real ints or strings, such as a database column, a JSON field, or a comparison with user input.
from enum import Enum
class Color(Enum):
RED = 1
print(Color.RED == 1) # False
print(Color.RED.value == 1) # TrueIntEnum and StrEnum solve this by mixing the enum with a built-in type. Each member is an instance of both the enum class and int or str.
IntEnum
An IntEnum member is an int. It compares equal to integers, orders against them, and works anywhere an integer is accepted.
from enum import IntEnum
class Priority(IntEnum):
LOW = 1
MEDIUM = 2
HIGH = 3
print(Priority.HIGH == 3) # True
print(Priority.LOW < Priority.HIGH) # True
print(Priority.HIGH + 1) # 4
print(sorted([Priority.HIGH, Priority.LOW, Priority.MEDIUM]))
print(isinstance(Priority.LOW, int)) # TrueArithmetic returns a plain int, not a member, so Priority.HIGH + 1 is 4. Ordering is the main reason to pick IntEnum: levels such as priority or severity can be compared with < and >.
StrEnum
StrEnum was added in Python 3.11. Its members are str instances, and the value must be a string. When you format one, you get the value, not the class-qualified name.
from enum import StrEnum
class Mode(StrEnum):
READ = "r"
WRITE = "w"
print(Mode.READ == "r") # True
print(f"{Mode.READ}") # r
print(str(Mode.WRITE)) # w
print(Mode.READ.upper()) # R
print(Mode("w")) # Mode.WRITEBecause members are strings, they can be passed to open(), used as dictionary keys interchangeably with the plain string, and serialized by json.dumps without extra work. StrEnum can also use auto(), which produces the lowercase member name as the value.
from enum import StrEnum, auto
class Fruit(StrEnum):
APPLE = auto()
PEAR = auto()
print(Fruit.APPLE.value) # appleHow the mixin works
Because the built-in type comes first in the inheritance order, its ==, <, and hash behavior wins over the plain Enum behavior. You can build the same thing yourself with class Mode(str, Enum). That form works before Python 3.11, but it formats as Mode.READ in f-strings on newer versions, which is why StrEnum exists.
Choosing between them
| Need | Choose |
|---|---|
| Members must never match raw values | `Enum` |
| Ordering or integer arithmetic, or an int-based protocol | `IntEnum` |
| Members passed as text to files, APIs or JSON | `StrEnum` |
| Combinable options | `Flag` (next chapter) |
The trade-off
The convenience weakens type safety. Two unrelated IntEnum classes compare equal when their values match.
from enum import IntEnum
class Shape(IntEnum):
CIRCLE = 1
class Size(IntEnum):
SMALL = 1
print(Shape.CIRCLE == Size.SMALL) # TrueA plain Enum would return False here. Use IntEnum and StrEnum when interoperability with ints or strings matters. Otherwise prefer Enum, so that mixing up values raises an error or fails the comparison instead of silently succeeding.
Common errors
- Using
StrEnumon Python older than 3.11 raisesImportError. Useclass X(str, Enum)there. - Giving
StrEnuma non-string value, such asA = 1, raisesTypeError. - Expecting arithmetic on
IntEnumto return a member. The result is a plainint.
Exercise
Given class Level(IntEnum): LOW = 1; HIGH = 3 and class Kind(StrEnum): A = "a", what do Level.LOW + 1, Level.HIGH > Level.LOW and Kind.A == "a" return, and what type is the first result?
Show answer
Level.LOW + 1 returns 2 as a plain int, not a Level member. Level.HIGH > Level.LOW returns True. Kind.A == "a" returns True, because StrEnum members are strings.
Exercise
Why might a plain Enum be a better choice than IntEnum for two unrelated sets of constants that both use the values 1, 2 and 3?
Show answer
Members of different IntEnum classes compare equal when their integer values match, so mistakes go unnoticed. Members of plain Enum classes never equal each other or raw ints, so such mistakes show up.