Sub topic 3
IntEnum, StrEnum, and Related Enum Patterns
This chapter assumes you know Python classes, decorators, functions, equality with ==, identity with is, and collection iteration.
IntEnum and StrEnum
IntEnum creates enum members that also behave like integers. StrEnum, available in Python 3.11 and later, creates members that behave like strings.
from enum import IntEnum, StrEnum
class Priority(IntEnum):
LOW = 1
HIGH = 3
class Mode(StrEnum):
READ = "r"
WRITE = "w"
print(Priority.HIGH == 3) # True
print(Priority.LOW < Priority.HIGH) # True
print(Mode.READ == "r") # True
print(f"{Mode.READ}") # rUse these mixins when compatibility with an existing integer or string API matters. Use plain Enum when you want stronger separation from raw values.
| Type | Best use | Example |
|---|---|---|
| `Enum` | Distinct domain values | `Color.RED` |
| `IntEnum` | Integer-compatible values | Status codes |
| `StrEnum` | String-compatible values | File modes |
Combining Options with `Flag`
Use Flag when one value can contain several independent options. The | operator combines members, and in tests membership.
from enum import Flag, auto
class Permission(Flag):
READ = auto()
WRITE = auto()
EXECUTE = auto()
access = Permission.READ | Permission.WRITE
print(Permission.READ in access) # True
print(Permission.EXECUTE in access) # FalseCommon Pitfalls
A plain enum member is not equal to its raw value:
from enum import Enum
class Color(Enum):
RED = 1
print(Color.RED == 1) # False
print(Color(1) is Color.RED) # TrueDo not choose IntEnum or StrEnum only to avoid conversion. Their compatibility can cause accidental comparisons with unrelated integers or strings. Also remember that duplicate values create aliases unless you use @unique`.
Functional API
The functional API is useful when member names come from configuration or another generated source.
from enum import Enum
Animal = Enum("Animal", "ANT BEE CAT")
print(Animal.BEE.value) # 2Customizing Lookup and Values
Override _missing_ to accept alternate input. Override _generate_next_value_ to define how auto() creates values.
from enum import StrEnum, auto
class Level(StrEnum):
@staticmethod
def _generate_next_value_(name, start, count, last_values):
return name.lower()
LOW = auto()
HIGH = auto()
@classmethod
def _missing_(cls, value):
if isinstance(value, str):
return cls(value.lower())
return None
print(Level("HIGH")) # Level.HIGHExercise
Which type should represent a combination of READ and WRITE permissions?
Show answer
Flag, because its members can be combined and tested independently.