Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 15 / Topic 4 of 6

Pattern matching, deep

Part 3 covered match/case with literals, the wildcard _, OR patterns ("sat" | "sun") and guards (case n if n > 100:). match can also look at the shape of a value: the type of an object and its fields, the length and parts of a sequence, or some of the keys of a mapping. Patterns can nest, and guards/OR patterns work inside nested patterns too. Think of airport security scanning a bag: not just "is it a bag", but "is it a bag shaped like this, with a laptop-shaped thing in this pocket".

Class patterns: match a type and its fields

from dataclasses import dataclass

@dataclass
class Circle:
    radius: float

@dataclass
class Rectangle:
    width: float
    height: float

def area(shape: object) -> float:
    match shape:
        case Circle(radius=r) if r > 0:
            return round(3.14159 * r * r, 2)
        case Rectangle(width=w, height=h):
            return round(w * h, 2)
        case Circle(radius=r):                 # r <= 0 lands here
            raise ValueError(f"radius must be positive, got {r}")
        case _:
            raise TypeError(f"unknown shape: {shape!r}")

print(area(Circle(3)))            # 28.27
print(area(Rectangle(4, 5)))      # 20

Circle(radius=r) only matches an instance of Circle (or a subclass); r captures the field named radius. @dataclass gives a class __match_args__ for free, so Circle(r) (positional) also works.

Sequence patterns: match a list's shape

def run_command(tokens: list[str]) -> str:
    match tokens:
        case ["move", x, y]:
            return f"move to ({x}, {y})"
        case ["say", *words] if words:         # guard: at least one word
            return "say: " + " ".join(words)
        case ["quit"] | ["exit"]:
            return "stopping"
        case []:
            return "no command"
        case _:
            return f"unknown command: {tokens}"

print(run_command(["move", "3", "4"]))         # move to (3, 4)
print(run_command(["say", "hello", "Asha"]))   # say: hello Asha

["move", x, y] matches a list of exactly 3 items whose first is "move". *words captures "everything else" into a list, like *args for function calls.

Mapping patterns: match some keys of a dict

def describe_response(data: dict) -> str:
    match data:
        case {"status": "ok", "rows": [first, *rest]}:    # nested sequence pattern
            return f"ok, {1 + len(rest)} row(s), first={first}"
        case {"status": "error", "code": code} if code >= 500:
            return f"server error {code}"
        case {"status": "error", "code": code}:
            return f"client error {code}"
        case {"status": status}:
            return f"unhandled status: {status}"
        case _:
            return "not a known response shape"

print(describe_response({"status": "ok", "rows": ["a", "b", "c"]}))   # ok, 3 row(s), first=a
print(describe_response({"status": "error", "code": 503}))           # server error 503

A mapping pattern matches if the listed keys are present with matching values; extra keys in the dict are ignored (unlike a sequence pattern, which cares about the whole length unless you add *rest).

Pattern kind Example Matches when
Class pattern case Circle(radius=r): the value is a Circle (or subclass); r captures radius
Sequence pattern case [a, b, *rest]: a list/tuple with at least 2 items; rest gets the remainder
Mapping pattern case {"status": "ok", **rest}: a dict that has that key/value; rest gets the other keys
Nested pattern case {"rows": [first, *_]}: patterns inside patterns, matched together
Guard case Circle(radius=r) if r > 0: the pattern matches, and the condition is true

๐Ÿ” Going deeper: a bare name in a pattern (case x:) always captures; a dotted name (case Color.RED:) or a literal is compared by value. Without **rest, a mapping pattern still only checks the keys you wrote, never the dict's full length.

Full program: examples/04_pattern_matching_deep.py.

Exercise 4: Toll fees, CLI args and config -- three kinds of pattern

Scenario: A toll booth prices vehicles by type and size, a tiny CLI parses a handful of commands, and a config loader reads a dict that may or may not have a "workers" list. What to do: Inside main():

  1. Write @dataclass classes Bike (no fields), Car(seats: int), Truck(axles: int).
  2. Write toll_fee(vehicle: object) -> int with a match: Bike() โ†’ 20; Car(seats=s) if s <= 4 โ†’ 60; any other Car โ†’ 100; Truck(axles=a) if a <= 2 โ†’ 150; any other Truck โ†’ 150 + (a - 2) * 50; anything else โ†’ raise TypeError(f"unknown vehicle: {vehicle!r}").
  3. Print the fee for Bike(), Car(4), Car(7), Truck(2), Truck(4) as f" {vehicle}: โ‚น{toll_fee(vehicle)}".
  4. Write parse_args(tokens: list[str]) -> str with a match: ["--help"] | ["-h"] โ†’ "help"; ["run", name, *rest] if rest โ†’ f"run {name} with {rest}"; ["run", name] โ†’ f"run {name}"; [] โ†’ "no args"; else โ†’ f"unknown args: {tokens}". Print the result for ["--help"], ["run", "server"], ["run", "server", "--port", "8000"], [].
  5. Write read_config(data: dict) -> str with a match: {"env": "prod", "debug": True} โ†’ "refusing: debug on in prod"; {"env": env, "workers": [first, *rest]} โ†’ f"{env}: {1 + len(rest)} worker(s), first={first}"; {"env": env} โ†’ f"{env}: default config"; else โ†’ "not a config". Print the result for {"env": "prod", "debug": True}, {"env": "staging", "workers": ["w1", "w2", "w3"]}, {"env": "dev"}, {"note": "empty"}.

Sample output:

-- toll fees --
  Bike(): โ‚น20
  Car(seats=4): โ‚น60
  Car(seats=7): โ‚น100
  Truck(axles=2): โ‚น150
  Truck(axles=4): โ‚น250
-- CLI args --
  ['--help'] -> help
  ['run', 'server'] -> run server
  ['run', 'server', '--port', '8000'] -> run server with ['--port', '8000']
  [] -> no args
-- config --
  {'env': 'prod', 'debug': True} -> refusing: debug on in prod
  {'env': 'staging', 'workers': ['w1', 'w2', 'w3']} -> staging: 3 worker(s), first=w1
  {'env': 'dev'} -> dev: default config
  {'note': 'empty'} -> not a config

๐Ÿ’ก Hint: @dataclass gives every class a repr like Car(seats=4) for free, which is why printing vehicle directly already looks right.


Show the solution to Exercise 4
"""Exercise 4: Toll fees, CLI args and config -- class, sequence and mapping patterns.

Shows: class patterns with a guard, sequence patterns, mapping patterns.

Run:   python ex04.py   (macOS/Linux: python3 ex04.py)
"""

from dataclasses import dataclass


@dataclass
class Bike:
    pass


@dataclass
class Car:
    seats: int


@dataclass
class Truck:
    axles: int


def toll_fee(vehicle: object) -> int:
    match vehicle:
        case Bike():
            return 20
        case Car(seats=s) if s <= 4:
            return 60
        case Car():                        # a bigger car, e.g. a van
            return 100
        case Truck(axles=a) if a <= 2:
            return 150
        case Truck(axles=a):
            return 150 + (a - 2) * 50
        case _:
            raise TypeError(f"unknown vehicle: {vehicle!r}")


def parse_args(tokens: list[str]) -> str:
    match tokens:
        case ["--help"] | ["-h"]:
            return "help"
        case ["run", name, *rest] if rest:
            return f"run {name} with {rest}"
        case ["run", name]:
            return f"run {name}"
        case []:
            return "no args"
        case _:
            return f"unknown args: {tokens}"


def read_config(data: dict) -> str:
    match data:
        case {"env": "prod", "debug": True}:
            return "refusing: debug on in prod"
        case {"env": env, "workers": [first, *rest]}:
            return f"{env}: {1 + len(rest)} worker(s), first={first}"
        case {"env": env}:
            return f"{env}: default config"
        case _:
            return "not a config"


def main() -> None:
    print("-- toll fees --")
    for vehicle in (Bike(), Car(4), Car(7), Truck(2), Truck(4)):
        print(f"  {vehicle}: โ‚น{toll_fee(vehicle)}")

    print("-- CLI args --")
    for args in (["--help"], ["run", "server"], ["run", "server", "--port", "8000"], []):
        print(f"  {args} -> {parse_args(args)}")

    print("-- config --")
    configs = [
        {"env": "prod", "debug": True},
        {"env": "staging", "workers": ["w1", "w2", "w3"]},
        {"env": "dev"},
        {"note": "empty"},
    ]
    for config in configs:
        print(f"  {config} -> {read_config(config)}")


if __name__ == "__main__":
    main()

Search the guide