brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's StrEnum makes enum members behave like plain strings

Python
~/tips/tip-python-enum-strenum-auto

from enum import StrEnum, auto

StrEnum members are real strings, and auto() gives each one its lowercase name.

Enums that need to be written to JSON, compared with config values or put in a log line used to need the (str, Enum) trick. Python 3.11 added StrEnum, which does that properly.

from enum import StrEnum, auto

class Color(StrEnum):
    RED = auto()
    GREEN = "green"

print(Color.RED, Color.GREEN)
print(Color.RED == "red", f"{Color.GREEN}!")
print(Color("red"))

That printed red green, then True green!, then red. The members compare equal to plain strings, work in f-strings without .value, and you can look one up by its string. json.dumps({'k': Color.RED}) writes a plain string too.

auto() in a StrEnum uses the lowercased member name as the value. Spell the value out when you want something else, as I did for GREEN.

One caveat: a lookup with a value that does not exist, like Color("blue"), raises ValueError. If the input comes from outside, catch that. Also, StrEnum needs Python 3.11, so on older versions the import fails.

Multi-word names and iteration behave as you’d hope. On Python 3.11.18, a member DARK_BLUE = auto() gets the value dark_blue, and [c.value for c in Color] gives ['red', 'green', 'dark_blue']. The failed lookup Color("blue") raises ValueError: 'blue' is not a valid Color.

The older pattern differs in one spot. With class Old(str, Enum), an f-string of Old.A gave Old.A on that same version, not the value. A StrEnum member prints as its value in both str() and f-strings.

Further reading: enum.StrEnum

More Python tips import asyncio except* ValueError as eg: import pytest pytest --maxfail=2 from functools import cached_property All Python tips (107) All topics

Link