How to Use StrEnum with auto() in Python
Define string-valued enum members automatically by using StrEnum with the auto() helper, making each member's value its own uppercase name.
Python code
20 linesfrom enum import StrEnum, auto
class Color(StrEnum):
RED = auto()
GREEN = auto()
BLUE = auto()
class Language(StrEnum):
PYTHON = auto()
JAVASCRIPT = auto()
RUST = auto()
print(list(Color))
print(list(Language))
print(Color.RED == "RED")
print(Language.PYTHON == "PYTHON")
print(f"Color: {Color.GREEN}, type: {type(Color.GREEN).__name__}")
print(f"Language: {Language.RUST}, type: {type(Language.RUST).__name__}")
Output
[<Color.RED: 'RED'>, <Color.GREEN: 'GREEN'>, <Color.BLUE: 'BLUE'>]
[<Language.PYTHON: 'PYTHON'>, <Language.JAVASCRIPT: 'JAVASCRIPT'>, <Language.RUST: 'RUST'>]
True
True
Color: GREEN, type: Color
Language: RUST, type: Language
How it works
The StrEnum class is a subclass of both str and Enum, so every member behaves exactly like a string while keeping enum semantics. When auto() is used inside a StrEnum, Python automatically assigns the member's name as its value—uppercased and identical to the attribute name. This removes the need to write explicit string assignments like RED = "RED". The list(Color) call iterates members in declaration order, printing repr values that show both name and value. Because StrEnum mixes in str, equality with plain strings works directly, and f"{Color.GREEN}" renders the string value rather than the enum repr.
Common mistakes
- Using `auto()` with regular `Enum` instead of `StrEnum`, which produces integer values like 1, 2, 3 instead of strings
- Forgetting that `StrEnum` requires Python 3.11+, leading to import errors on older interpreters
- Assuming member values will be lowercase or custom—`auto()` always uses the uppercase member name
Variations
- Assign explicit values: `RED = "red"` to use lowercase strings instead of auto-generated names
- Use `class Color(str, Enum)` for compatibility with Python 3.10 or earlier
- Iterate with `Color.__members__` to get a dict of name-to-member pairs
Real-world use cases
- Representing HTTP status constants like OK, NOT_FOUND where the string equals the member name for serialization.
- Defining named log levels (INFO, WARN, ERROR) that integrate naturally with string-based log formatters.
- Modeling database column names or API field keys as enum members for type-safe string references.
Sponsored
More from OOP & classes
- Add property getter setter validation in Python easy
- Binary Tree Inorder Traversal in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
Keep learning
Related tutorials and quizzes for this topic.