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 look members up by value. It also assumes you know the difference between == and is, and that you can read a class that inherits from another class. The examples use Python 3.11 or newer, because StrEnum was added in 3.11. Version differences are called out where they matter.
Why a plain Enum is not enough sometimes
A plain Enum member is its own kind of object. It never equals its raw value:
from enum import Enum
class Color(Enum):
RED = 1
print(Color.RED == 1) # FalseThis is usually what you want, because it stops you from mixing up unrelated constants. It becomes a nuisance when you replace existing integer or string constants with an enum. Code that already passes 200 to a function, compares against "r", or writes values into JSON would all break.
IntEnum and StrEnum solve this. Their members are real int and str objects that also belong to an enum, so they keep working wherever the old constants were used.
IntEnum: members that are integers
Subclass IntEnum instead of Enum:
from enum import IntEnum
class HttpStatus(IntEnum):
OK = 200
NOT_FOUND = 404
SERVER_ERROR = 500
print(HttpStatus.OK == 200) # True
print(HttpStatus.OK < HttpStatus.NOT_FOUND) # True
print(sorted([HttpStatus.SERVER_ERROR, HttpStatus.OK]))
# [<HttpStatus.OK: 200>, <HttpStatus.SERVER_ERROR: 500>]
print({200: "fine"}[HttpStatus.OK]) # fine
print(["a", "b", "c"][IntEnum("Idx", "X Y Z").Z]) # cEach of these works because HttpStatus.OK is an int:
- It compares equal to
200. - It supports ordering with
<,>,<=and>=. A plainEnumraisesTypeErrorfor these. - It has the same hash as
200, so it finds the same dictionary entry. - It can be used as a list index.
The standard library uses this approach itself. http.HTTPStatus is an IntEnum, which is why you can pass HTTPStatus.NOT_FOUND to code that expects 404.
Lookup by value and by name still works as before: HttpStatus(404) returns HttpStatus.NOT_FOUND, and HttpStatus["OK"] returns HttpStatus.OK. Lookup by value is strict about type. HttpStatus("404") raises ValueError, because the string "404" does not equal any member.
Arithmetic gives plain ints
Operations on an IntEnum member return an ordinary int, not a member:
from enum import IntEnum
class Priority(IntEnum):
LOW = 1
HIGH = 3
result = Priority.LOW + 1
print(result) # 2
print(type(result)) # <class 'int'>
print(Priority.LOW + 1 == Priority.HIGH) # FalsePriority.LOW + 1 is 2, and no member has the value 2. Python does not try to convert the result back, so you get an int. If you need a member, call Priority(result). That call raises ValueError when no member has the value.
Printing
In Python 3.11 and newer, str() and format() of an IntEnum member produce the number, while repr() still shows the enum:
from enum import IntEnum
class Priority(IntEnum):
LOW = 1
print(str(Priority.LOW)) # 1
print(f"{Priority.LOW}") # 1
print(repr(Priority.LOW)) # <Priority.LOW: 1>Python 3.10 and earlier printed Priority.LOW from str() but 1 from f-strings. If your code must run on older versions, do not depend on the text form.
StrEnum: members that are strings
StrEnum does the same for strings. Every value must be a string.
import json
from enum import StrEnum, auto
class Mode(StrEnum):
READ = "r"
WRITE = "w"
class Fruit(StrEnum):
APPLE = auto()
BLUE_BERRY = auto()
print(Mode.READ == "r") # True
print(f"mode={Mode.WRITE}") # mode=w
print("open:" + Mode.READ) # open:r
print(Mode.READ.upper()) # R
print({"r": "reading"}[Mode.READ]) # reading
print(json.dumps({"mode": Mode.READ})) # {"mode": "r"}
print(Fruit.BLUE_BERRY.value) # blue_berryThree things are worth noticing:
str(member)and f-strings return the value itself, notMode.READ.auto()in aStrEnumproduces the lowercase member name. Plainauto()produces1, 2, 3, which would not be valid string values.- Because members are real strings,
json.dumpswrites them as ordinary JSON strings with no custom encoder.
StrEnum is a good fit for values that cross a boundary as text: command-line options, JSON fields, database columns, and HTTP parameters.
Before Python 3.11
You can get most of the behavior by mixing the base types yourself:
from enum import Enum
class Mode(str, Enum):
READ = "r"
WRITE = "w"
print(Mode.READ == "r") # True
print(str(Mode.READ)) # Mode.READThe difference is in printing. str() of this class returns Mode.READ, and format() output changed between versions (3.12 changed it again). StrEnum fixes the text form so it always returns the value. On 3.11 and newer, prefer StrEnum and IntEnum over the manual mixin.
How the mixin works
The mixin classes are shaped like this:
classDiagram
class Enum
class ReprEnum
class int
class str
class IntEnum
class StrEnum
Enum <|-- ReprEnum
ReprEnum <|-- IntEnum
ReprEnum <|-- StrEnum
int <|-- IntEnum
str <|-- StrEnumIntEnum inherits from both int and ReprEnum, and StrEnum inherits from both str and ReprEnum. ReprEnum is a small Enum subclass that keeps the str() and format() of the mixed-in type. That is why the text form is the plain value. In the actual enum module the order and detail differ slightly, but this is the working model.
The diagram above is for orientation, so it carries no code. Here is the same structure as a check you can run:
from enum import Enum, IntEnum, StrEnum
print(issubclass(IntEnum, int), issubclass(IntEnum, Enum)) # True True
print(issubclass(StrEnum, str), issubclass(StrEnum, Enum)) # True TruePitfalls specific to these classes
Members of different enums can be equal
Equality follows the underlying value, not the enum class:
from enum import IntEnum
class Color(IntEnum):
RED = 1
class Shape(IntEnum):
CIRCLE = 1
print(Color.RED == Shape.CIRCLE) # True
print(Color.RED is Shape.CIRCLE) # FalseThis is the cost of behaving like an int. A plain Enum would return False here and catch the mistake. If you do not need numeric behavior, do not use IntEnum.
Falsy members
A plain Enum member is always truthy. An IntEnum member follows int rules, so a member with value 0 is falsy:
from enum import IntEnum
class Level(IntEnum):
NONE = 0
SOME = 1
print(bool(Level.NONE)) # False
print(bool(Level.SOME)) # TrueA check such as if level: then means "level is not NONE", which may or may not be what you meant. Compare explicitly with level is Level.NONE when the difference matters.
Aliases and accidental matches
Because members compare equal to plain values, a stray literal can pass a comparison without anyone noticing. if status == 404: works, but it hides the intent that HttpStatus.NOT_FOUND expresses. Use member names in your own code. Rely on the int or str behavior at the boundaries, such as parsing input or calling older APIs.
Not every value is accepted
StrEnum requires string values. class Bad(StrEnum): A = 1 raises TypeError when the class is defined. For IntEnum, values must be integers, so A = "x" fails with ValueError.
Choosing between Enum, IntEnum and StrEnum
| Situation | Use |
|---|---|
| Named choices that should never be confused with raw numbers or strings | `Enum` |
| Replacing integer constants, or you need ordering and arithmetic | `IntEnum` |
| Values that travel as text (JSON, CLI flags, database fields) | `StrEnum` |
| Combinable options | `Flag`, covered in the next chapter |
Putting it together
This example parses a log level from text, compares levels, and writes the result as JSON:
import json
from enum import IntEnum
class LogLevel(IntEnum):
DEBUG = 10
INFO = 20
ERROR = 40
def parse(text: str) -> LogLevel:
return LogLevel[text.upper()]
def should_log(message_level: LogLevel, threshold: LogLevel) -> bool:
return message_level >= threshold
level = parse("info")
print(level) # 20
print(should_log(LogLevel.ERROR, level)) # True
print(should_log(LogLevel.DEBUG, level)) # False
print(json.dumps({"level": level})) # {"level": 20}
print(LogLevel(40).name) # ERRORparse uses name lookup, which raises KeyError for an unknown name such as "loud". The comparison relies on ordering, which only IntEnum provides. The JSON output relies on the member being an int. Each of these needs a different part of the IntEnum behavior.
Exercise
Given class Color(IntEnum): RED = 1 and class Shape(IntEnum): CIRCLE = 1, what do Color.RED == Shape.CIRCLE and Color.RED is Shape.CIRCLE return, and why? Which base class would make the first comparison return False?
Show answer
The first returns True and the second returns False. Both members are ints with the value 1, so == compares them as ints. They are different objects, so is returns False. Changing both classes to plain Enum makes == return False, because plain Enum members compare equal only to themselves.
Exercise
On Python 3.11 or newer, what does this print? class Fruit(StrEnum): APPLE = auto(); KIWIFRUIT = auto() followed by print(f"{Fruit.KIWIFRUIT}", Fruit.APPLE.value).
Show answer
It prints "kiwi_fruit apple". In a StrEnum, auto() uses the lowercase member name as the value, and f-string formatting of a StrEnum member gives its value.
Exercise
Why does Priority.LOW + 1 == Priority.HIGH return False when LOW is 1 and HIGH is 3, and how would you get the member for the result of an addition when a member with that value exists?
Show answer
Priority.LOW + 1 is the plain int 2, and 2 does not equal 3. Arithmetic on IntEnum members returns an int, not a member. To get a member back, call the class with the result, for example Priority(2), which raises ValueError if no member has that value.