enum StrEnum Parses Config Modes
Parse config strings into enum members with StrEnum, whose members are real strings, and fall back to plain Enum when members carry separate payloads.
Code
from enum import Enum, StrEnum
# StrEnum(3.11+):成员本身就是字符串,比较与序列化无需 .value
class Mode(StrEnum):
ACCUMULATE = "accumulate"
APPEND = "append"
REPLACE = "replace"
def parse_mode(raw: str) -> Mode:
# 按值查找:非法配置输入抛 ValueError,即刻暴露而不是静默放行
return Mode(raw.lower())
for raw in ["Append", "replace"]:
mode = parse_mode(raw)
print(f"{raw!r} -> {mode}")
# 普通枚举:成员带独立载荷,name 与 value 分离
class Retry(Enum):
FAST = 1
SLOW = 2
print(Retry.FAST.name, Retry.SLOW.value)
try:
parse_mode("turbo")
except ValueError as error:
print("rejected:", error)Output
Captured from a sandboxed run of this snippet in the build pipeline.
'Append' -> append
'replace' -> replace
FAST 2
rejected: 'turbo' is not a valid ModeHow the snippet works
The working surface is the classes Mode and Retry and the function parse_mode — everything else is wiring.
Iteration happens inside for raw in ["Append", "replace"] — everything outside it runs once.
Using it
The main signature reads def parse_mode(raw: str) -> Mode
Running the file prints labeled results such as rejected: — each operation’s effect is visible in the output.
The surface worth importing is parse_mode; the helpers around it are private to the snippet.
Key statements
def parse_mode(raw: str) -> Mode:
# 按值查找:非法配置输入抛 ValueError,即刻暴露而不是静默放行
return Mode(raw.lower())
except ValueError as error:
print("rejected:", error)
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. Every import resolves inside the standard library — `enum`. The file defines `parse_mode` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.