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.

Easy Python 3.11+ Aug 9, 2026 OOP & classes 13 views 0 copies

Python code

20 lines
Python 3.11+
from 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

stdout
[<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

  1. Assign explicit values: `RED = "red"` to use lowercase strings instead of auto-generated names
  2. Use `class Color(str, Enum)` for compatibility with Python 3.10 or earlier
  3. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from OOP & classes

Related tutorials and quizzes for this topic.