Command Palette

Search for a command to run...

Hectal
Phase 10: Type Hints and Modern Python
Python · Exercise 5 of 5 Previous
Advanced

Describe commands with match

The starter defines four dataclasses: Move(dx, dy), Say(text), Quit() and Unknown(text). Write describe(cmd) using match with class patterns that returns "move by 3, 4" for Move(3, 4), "say: hi" for Say("hi"), "bye" for Quit() and "unknown: xyz" for Unknown("xyz").

Also make Move(0, 0) return "stay": give it its own case and put that case before the general Move case, because the first matching case wins. Anything that is not one of the four classes should end in assert_never(cmd) in the last case.

What Check tests

  1. Move(3, 4) gives move by 3, 4
  2. Move(0, 0) gives stay
  3. Only the exact origin is stay
  4. Say, Quit and Unknown are described
  5. The function uses match and case
  6. Anything else raises AssertionError through assert_never
  7. The program prints the first description

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

main.py
Sign in to run your code.

Output

Press Run to see what your program prints.