SoFunction
Updated on 2025-04-13

Detailed explanation of the process control statement match-case in Python

Detailed explanation of match-case grammar and actual combat

match-caseIt is a pattern matching syntax introduced in Python 3.10+, which can replace the traditionalif-elif-elseChain, supports complex data deconstruction and conditional combination.

The following are 6 core usage scenarios and code cases:

1. Basic value matching (similar to switch-case)

# Match HTTP status codestatus_code = 418

match status_code:
    case 200:
        print("✅ Success")
    case 301 | 302 | 307:
        print("↪️ Redirect")
    case 400 | 401 | 403:
        print("❌ Client Error")
    case 500:
        print("🔥 Server Error")
    case _:
        print(f"Unknown status: {status_code}")
        
Output:Unknown status: 418

2. Data structure deconstruction and matching

Scenario 1: List destruction

def parse_command(cmd: list):
    match cmd:
        case ["start", *args]:
            print(f"🚀 Start the service,parameter: {args}")
        case ["stop", service_name]:
            print(f"🛑 Stop service: {service_name}")
        case ["restart"]:
            print("🔃 Restart the service")
        case _:
            print("⚠️ Invalid command")

parse_command(["start", "--port=8080"])  # 🚀 Start the service, parameters: ['--port=8080']parse_command(["stop", "nginx"])         # 🛑 Stop service: nginx

Scene 2: Dictionary Deconstruction

user_data = {
    "name": "John",
    "age": 25,
    "address": {"city": "New York", "zip": "10001"}
}

match user_data:
    case {"name": str(name), "age": int(age), "address": {"city": city}}:
        print(f"👤 {name} ({age}age) From {city}")
    case {"name": _, "age": int(age)} if age < 0:
        print("⛔ Age cannot be negative")
    case _:
        print("❓ Data format error")

# Output: 👤 John (25 years old) from New York

3. Class instance pattern matching

class Vector:
    def __init__(self, x, y, z=0):
         = x
         = y
         = z

def analyze_vector(vec):
    match vec:
        case Vector(0, 0, 0):
            print("⭕ Zero vector")
        case Vector(x=0, y=0):
            print("📐 Z-axis vector")
        case Vector(x, y, z) if x == y == z:
            print("🔶 Cube Diagonal")
        case Vector(_, _, z) if z != 0:
            print(f"🚀 Three-dimensional vector (Z={z})")
        case _:
            print("📏 Normal two-dimensional vector")

analyze_vector(Vector(0, 0, 0))   # ⭕ Zero vectoranalyze_vector(Vector(2, 2, 2))   # 🔶 Cube diagonal

4. Advanced matching with guard conditions

def process_transaction(tx):
    match tx:
        case {"type": "deposit", "amount": amt} if amt > 0:
            print(f"💰 Save {amt} Yuan")
        case {"type": "withdraw", "amount": amt, "balance": bal} if amt <= bal:
            print(f"💸 take out {amt} Yuan")
        case {"type": "withdraw", "amount": amt}:
            print(f"⛔ Insufficient balance,尝试take out {amt} Yuan")
        case {"type": _}:
            print("❌ Invalid transaction type")

process_transaction({"type": "withdraw", "amount": 500, "balance": 1000})
# Output:💸 take out 500 Yuan

5. Type verification and combination matching

def handle_data(data):
    match data:
        case int(n) if n % 2 == 0:
            print(f"🔢 even: {n}")
        case float(f) if f > 100.0:
            print(f"📈 Large floating point number: {f:.2f}")
        case str(s) if len(s) > 50:
            print("📜 Long text (truncated):", s[:50] + "...")
        case list([int(x), *rest]):
            print(f"📦 Integer list,First element: {x}, length: {len(rest)+1}")
        case _:
            print("❓ Unknown data type")

handle_data(42)            # 🔢 Even number: 42handle_data([10, 20, 30])  # 📦 Integer list, first element: 10, length: 3

6. Protocol analysis practical cases

def parse_packet(packet: bytes):
    match packet:
        case b'\x08\x00' | b'\x08\x01':
            print("📡 ICMP packet")
        case b'\x45' + payload:
            print(f"🌐 IPv4 Data Packet,Load length: {len(payload)}")
        case [version, _, *rest] if version >> 4 == 6:
            print("🌐 IPv6 packet")
        case _:
            print("❌ Unknown Agreement")

parse_packet(b'\x45\x00\x00\x1c\x00\x01\x00\x00\x40')  # 🌐 IPv4 Data Packet...

Notes on using:

  • Version requirements: Only support Python 3.10+
  • Match order: execute in code order, the first match will be terminated if it is successful
  • Wildcard _: Must be placed last to match all unprocessed cases
  • Performance optimization: Complex pattern matching may affect performance and avoid deep nesting

Comparison with traditional writing:

  • Scene match-case writing method if-elif Traditional writing method
  • Multi-condition value matching Use operator concise combinations require duplicate or connection conditions
  • Dictionary nested deconstruction Directly extract multi-level fields Multi-layer get( ) Check and type verification
  • Class attribute check Direct matching object attributes Require isinstance() and attribute access
  • Combination condition case + if guard condition complex boolean expression is required
  • By using match-case rationally, the code can be made more concise and easy to read, especially suitable for scenarios such as protocol parsing, API response processing, and complex business rule judgment. It is recommended to use Type Hints with better results!

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.