Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 8.9 — Enums
Python · Example 2 of 2 Python 3.11+

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.

01

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.

02

Write a StrEnum called Role with USER, ASSISTANT and SYSTEM (lowercase text values). Parse "assistant" into a member and print role == "assistant".

03

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

01

What problem do enums solve, and how do you define one?

02

How do you look up an enum member by value and by name, and what if the value is invalid?

03

What is the difference between Enum, IntEnum and StrEnum?

04

How do enums work with match, and what is the capture-pattern trap?

StrEnum, match, methods and parsing at the edge Python 3.11+
Sign in to run this example in your browser.

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>]