Command Palette

Search for a command to run...

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

Enum, auto, IntEnum and Flag

Try Color(3), Color['GREEN'] and Color.RED < Color.BLUE (that last one raises TypeError, because a plain Enum has no ordering).

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?

Enum, auto, IntEnum and Flag
Sign in to run this example in your browser.

Expected output

Color.RED
<Color.RED: 1>
RED 1
Color.GREEN Color.BLUE
[<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 3>]
['RED', 'GREEN', 'BLUE']
True False
False
True
1 RED
2 GREEN
3 BLUE
ValueError: 9 is not a valid Color
[('FIRST', 1), ('SECOND', 2), ('THIRD', 3)]
True True 6 [<Level.LOW: 1>, <Level.HIGH: 10>]
Perm.READ|WRITE
True False
Perm(0) Perm.WRITE