iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Python Match

Python 3.10 added match / case — structural pattern matching. More powerful than a switch statement, it can destructure values as it tests them.

Basic shape

PYTHON
def describe(status):
    match status:
        case 'paid':       return 'OK'
        case 'pending':    return 'Awaiting'
        case 'refunded':   return 'Refund issued'
        case _:            return 'Unknown'

The _ case is the wildcard — matches anything.

Destructuring

PYTHON
def location(point):
    match point:
        case (0, 0):           return 'origin'
        case (x, 0):           return f'x-axis at {x}'
        case (0, y):           return f'y-axis at {y}'
        case (x, y):           return f'({x}, {y})'

Class patterns

PYTHON
from dataclasses import dataclass

@dataclass
class Point: x: int; y: int

def describe(p):
    match p:
        case Point(x=0, y=0): return 'origin'
        case Point(x=x, y=0): return f'x-axis at {x}'
        case Point():         return 'somewhere'

Guards

PYTHON
match age:
    case n if n < 13: print('child')
    case n if n < 20: print('teen')
    case _:           print('adult')
Tip: If your match only has equality cases against constants, a dict lookup is often more idiomatic: RESPONSES.get(status, 'Unknown').

Example

Example
# Python 3.10+
status = 'paid'
match status:
    case 'paid':       print('OK')
    case 'pending':    print('Awaiting')
    case 'refunded':   print('Refund issued')
    case _:            print('Unknown')
Try it Yourself »

Exercise

Wildcard pattern that matches anything.

case : print('default')

Test yourself

Q1. match was added in Python…
Q2. The wildcard case is…
Q3. A guard in a case looks like…

Discussion

Loading…