StrEnum, match, methods and parsing at the edge
StrEnum needs Python 3.11 and match needs Python 3.10. Add a new finish reason and notice that next_action returns None until you add a case. In Role.parse, raise ... from None hides the earlier error so the learner sees only the clear message (Topic 7.2).
An enum is a fixed set of named constants, such as Color.RED or FinishReason.STOP. Enums replace magic numbers and loose strings with names that are checked, listable and safe to compare, and they pair naturally with match.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write an enum Weekday with MONDAY to SUNDAY using auto(), and a function is_weekend(day) that returns True for Saturday and Sunday. Test Weekday.SUNDAY and Weekday.MONDAY.
Write a StrEnum called Role with USER, ASSISTANT and SYSTEM (lowercase text values). Parse "assistant" into a member and print role == "assistant".
Write a function describe(level) using match on an IntEnum Level with LOW = 1, HIGH = 3 that returns "relax" or "hurry".
Explain it without notes
What problem do enums solve, and how do you define one?
How do you look up an enum member by value and by name, and what if the value is invalid?
What is the difference between Enum, IntEnum and StrEnum?
How do enums work with match, and what is the capture-pattern trap?
Expected output
length True LENGTH
finished because: length
STOP -> show the answer
LENGTH -> ask the model to continue
TOOL_CALLS -> run the requested tools
9.82 3.7
Msg(role=<Role.USER: 'user'>, text='hi')
ValueError: unknown role: robot
True [<Shape.SQUARE: 1>]