Python - Pattern Matching (match/case)

Overview

Estimated time: 25–35 minutes

Structural pattern matching (match/case) provides a powerful way to deconstruct and branch on data. Learn syntax, use cases, and pitfalls.

Learning Objectives

  • Use match/case with literals, sequences, mappings, class patterns, and guards.
  • Avoid accidental name capture; understand _ wildcard and case _ default.
  • Choose pattern matching appropriately vs if/elif or dispatch tables.

Prerequisites

  • Python 3.10+; familiarity with basic data structures

Examples

def http_status(code):
    match code:
        case 200:
            return "OK"
        case 404:
            return "Not Found"
        case _:
            return "Other"

print(http_status(404))

Expected Output:

Not Found

Guidance & Patterns

point = (0, 5)
match point:
    case (0, y):
        print("on Y axis at", y)
    case (x, 0):
        print("on X axis at", x)
    case (x, y) if x == y:
        print("on diagonal", x)
    case _:
        print("somewhere else")

Best Practices

  • Prefer explicit class patterns with data classes to keep matching robust to shape changes.
  • Beware name capture: bare names in patterns bind; use value == guards or case [*_, value] forms carefully.

Exercises

  1. Match JSON-like dicts to handle different message types ({type: 'event', ...}).
  2. Use class patterns with a @dataclass representing shapes (Circle, Rectangle) and compute areas.