typestar

Structural pattern matching, further in Python

Class patterns, guards, and capturing the rest of a mapping.

from dataclasses import dataclass


@dataclass
class Click:
    x: int
    y: int


def describe(event):
    match event:
        case {"kind": "key", "value": str(key)} if len(key) == 1:
            return f"key {key}"
        case {"kind": "key", **rest}:
            return f"odd key event {sorted(rest)}"
        case Click(x=0, y=0):
            return "origin click"
        case Click(x=x, y=y):
            return f"click at {x},{y}"
        case [first, *others]:
            return f"batch of {1 + len(others)} starting {first!r}"
        case _:
            return "unknown"


for event in [{"kind": "key", "value": "a"}, Click(0, 0), Click(3, 4),
              ["a", "b"], 7]:
    print(describe(event))

How it works

  1. A class pattern matches type and attributes together.
  2. {**rest} captures the keys you did not name.
  3. | combines alternatives in one case.

Keywords and builtins used here

The run, in numbers

Lines
28
Characters to type
565
Tokens
212
Three-star pace
105 tpm

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

Type this snippet

Step 3 of 3 in Data & enums, step 47 of 53 in Pythonic Python.

← Previous Next →