Created
January 26, 2026 09:19
-
-
Save bbelderbos/1525b9a80015c1c4d7ffa7fe88550dea to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 1) Literal patterns: Cleanly dispatch on exact values (great for status codes and enums). | |
| def handle_response(status: int) -> str: | |
| match status: | |
| case 200: | |
| return "OK" | |
| case 404: | |
| return "Not Found" | |
| case 500: | |
| return "Server Error" | |
| case _: | |
| return "Unknown" | |
| assert handle_response(200) == "OK" | |
| assert handle_response(404) == "Not Found" | |
| assert handle_response(500) == "Server Error" | |
| assert handle_response(418) == "Unknown" | |
| # 2) Sequence patterns: Parse tokenized commands without manual indexing; supports “rest” capture for variable args. | |
| def process_command(command: str) -> str | int: | |
| match command.split(): | |
| case ["quit"]: | |
| return "Goodbye!" | |
| case ["hello", name]: | |
| return f"Hello, {name}!" | |
| case ["add", *numbers]: | |
| return sum(int(n) for n in numbers) | |
| case _: | |
| return "Unknown command" | |
| assert process_command("hello Alice") == "Hello, Alice!" | |
| assert process_command("add 1 2 3 4") == 10 | |
| assert process_command("quit") == "Goodbye!" | |
| assert process_command("wat") == "Unknown command" | |
| assert process_command("add") == 0 # empty sum | |
| # 3) Mapping patterns: Match dict payloads by required keys (extra keys can still match) and route events safely. | |
| def handle_event(event: dict) -> str: | |
| match event: | |
| case {"type": "click", "x": x, "y": y}: | |
| return f"Clicked at ({x}, {y})" | |
| case {"type": "keypress", "key": key}: | |
| return f"Pressed {key}" | |
| case {"type": "error", "message": msg}: | |
| raise ValueError(msg) | |
| case _: | |
| return "Unknown event" | |
| assert handle_event({"type": "click", "x": 1, "y": 2}) == "Clicked at (1, 2)" | |
| assert handle_event({"type": "keypress", "key": "Enter"}) == "Pressed Enter" | |
| assert ( | |
| handle_event({"type": "click", "x": 1, "y": 2, "button": "left"}) | |
| == "Clicked at (1, 2)" | |
| ) # extra keys ok | |
| assert handle_event({"type": "noop"}) == "Unknown event" | |
| try: | |
| handle_event({"type": "error", "message": "boom"}) | |
| raise AssertionError("Expected ValueError") | |
| except ValueError as e: | |
| assert str(e) == "boom" | |
| # 4) Guards + type patterns: Combine type checks and conditions to express branching rules succinctly. | |
| def categorize(value) -> str: | |
| match value: | |
| case int() | float() if value < 0: | |
| return "negative number" | |
| case int() | float() if value > 0: | |
| return "positive number" | |
| case int() | float(): | |
| return "zero" | |
| case str(): | |
| return "string" | |
| case _: | |
| return "other" | |
| assert categorize(-1) == "negative number" | |
| assert categorize(-1.5) == "negative number" | |
| assert categorize(2) == "positive number" | |
| assert categorize(2.5) == "positive number" | |
| assert categorize(0) == "zero" | |
| assert categorize(0.0) == "zero" | |
| assert categorize("x") == "string" | |
| assert categorize(None) == "other" | |
| # 5) Class patterns: Pattern match dataclass instances for readable, declarative domain logic. | |
| from dataclasses import dataclass # noqa E402 | |
| @dataclass | |
| class Point: | |
| x: int | |
| y: int | |
| def describe(point: Point) -> str: | |
| match point: | |
| case Point(x=0, y=0): | |
| return "origin" | |
| case Point(x=0, y=y): | |
| return f"on y-axis at {y}" | |
| case Point(x=x, y=0): | |
| return f"on x-axis at {x}" | |
| case Point(): | |
| return "somewhere else" | |
| assert describe(Point(0, 0)) == "origin" | |
| assert describe(Point(0, 3)) == "on y-axis at 3" | |
| assert describe(Point(5, 0)) == "on x-axis at 5" | |
| assert describe(Point(2, 2)) == "somewhere else" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Code