typestar

Structural pattern matching in Python

match/case: branching on the shape of data, not just its value.

def describe(command):
    match command.split():
        case ["go", direction]:
            return f"walking {direction}"
        case ["look"]:
            return "you see a wall of code"
        case ["take", *items]:
            return f"picked up {len(items)} items"
        case _:
            return "unknown command"


print(describe("go north"))
print(describe("take sword shield"))

How it works

  1. Each case tries to fit the split command list.
  2. Patterns capture parts into names like direction.
  3. *items matches a variable-length tail.
  4. case _ is the catch-all fallback.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
308
Tokens
88
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 59 seconds.

Type this snippet

Step 4 of 7 in Flow control, step 19 of 72 in Language basics.

← Previous Next →