AW Dev Rethought

βœ‚οΈ Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away - Antoine de Saint-ExupΓ©ry

πŸ’‘ 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!