💡 Python QuickBits — 🧩 Pattern Matching in Python 3.10+


Description:

Python 3.10 introduced structural pattern matching with match/case. It looks like switch/case, but it’s smarter — you can match not just values, but also dictionary structures (like JSON) and sequences (like CLI args).


📝 Basic Value Matching

Use match/case like a switch statement:

command = "start"

match command:
    case "start":
        print("Starting process...")
    case "stop":
        print("Stopping process...")
    case _:
        print("Unknown command")

📦 Pattern Matching JSON-like Data

You can match against a dict’s shape and extract fields directly:

import json

payload = json.loads('{"type": "user", "name": "Alice"}')

match payload:
    case {"type": "user", "name": name}:
        print(f"User record found: {name}")
    case {"type": "order", "id": order_id}:
        print(f"Order record found: {order_id}")
    case _:
        print("Unknown payload")

💻 Matching CLI Args (Sequence Pattern)

Match lists/tuples directly — useful for CLI-like inputs:

args = ["deploy", "staging"]

match args:
    case ["deploy", env]:
        print(f"Deploying to {env}")
    case ["rollback", env]:
        print(f"Rolling back {env}")
    case _:
        print("Unknown command args")

✅ Key Points

  • ✅ Cleaner than nested if/elif.
  • ✅ Works on values, dicts, and sequences.
  • ✅ Lets you extract variables inline.
  • 🐍 Available in Python 3.10 and above.

Code Snippet:

import json   # to simulate JSON payload parsing
import sys    # to simulate CLI args parsing


command = "start"

match command:                          # match on a string value
    case "start":
        print("Starting process...")
    case "stop":
        print("Stopping process...")
    case _:                             # default case
        print("Unknown command")


# Simulated JSON payload
payload = json.loads('{"type": "user", "name": "Alice"}')

match payload:
    case {"type": "user", "name": name}:      # extract 'name' if type=user
        print(f"User record found: {name}")
    case {"type": "order", "id": order_id}:   # match orders
        print(f"Order record found: {order_id}")
    case _:                                   # default
        print("Unknown payload")

 
 # Simulated CLI args
args = ["deploy", "staging"]

match args:
    case ["deploy", env]:
        print(f"Deploying to {env}")
    case ["rollback", env]:
        print(f"Rolling back {env}")
    case _:                                   # fallback
        print("Unknown command args")

Link copied!

Comments

Add Your Comment

Comment Added!