Pattern Matching

Advanced PythonPattern MatchingFree Lesson

Advertisement

Introduction

Structural pattern matching (match-case) for complex data structure inspection.

Basic Match

def http_status(status):
    match status:
        case 200:
            return "OK"
        case 404:
            return "Not Found"
        case 500:
            return "Server Error"
        case _:
            return "Unknown"

Patterns

# Variable pattern
match value:
    case x:
        print(f"Got: {x}")

# Wildcard
match value:
    case _:
        print("Default")

# Literal pattern
match command:
    case ["quit"]:
        print("Quitting")
    case ["move", x, y]:
        print(f"Move to {x}, {y}")

# OR pattern
match status:
    case 200 | 201 | 204:
        print("Success")

Class Patterns

from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float

@dataclass
class Circle:
    center: Point
    radius: float

def shape_info(shape):
    match shape:
        case Point(x=0, y=0):
            return "Origin"
        case Point():
            return "Some point"
        case Circle(center=Point(x=0, y=0), radius=r):
            return f"Centered circle, r={r}"

Practice Problems

  1. Implement calculator with match
  2. Parse command-line arguments
  3. Handle JSON-like structures
  4. Match nested patterns
  5. Use guards in patterns

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement