Python 3.13 新特性:更强大的模式匹配(支持字典/集合)

Python 3.13 对结构化模式匹配(match-case)进行了重大增强,新增了对字典和集合的原生支持。以下是核心特性和使用示例:


1. 字典模式匹配

可直接匹配字典的键值结构:

def process_data(data: dict):
    match data:
        # 匹配完整键值结构
        case {"type": "user", "name": str(name), "age": int(age)}:
            print(f"用户: {name}, 年龄: {age}")

        # 匹配部分键 + 通配符
        case {"type": "error", "code": int(code), **details}:
            print(f"错误 {code}: {details}")

        # 类型守卫
        case {"values": list(values)} if len(values) > 3:
            print(f"长列表: {values[:3]}...")

        case _:
            print("未知格式")


2. 集合模式匹配

支持无序集合的成员匹配:

def analyze_set(s: set):
    match s:
        # 匹配特定元素组合
        case {1, 2, 3}:
            print("包含基础数字集")

        # 匹配元素 + 通配符
        case {"apple", "banana", *fruits}:
            print(f"核心水果 + {len(fruits)}种其他")

        # 类型和大小守卫
        case {str(), str()} if len(s) == 2:
            print("两个字符串的集合")

        case _:
            print("其他集合")


3. 混合嵌套匹配

支持字典/集合的深度嵌套:

match config:
    case {
        "mode": "advanced",
        "filters": {"type": "include", "tags": {"urgent", "important"}}
    }:
        print("紧急重要任务模式")

    case {
        "backup": {"path": str(p), "format": "zip" | "tar"} as backup
    }:
        print(f"备份到 {p} ({backup['format']})")


关键优势:
  1. 通配符支持**rest 捕获剩余字典项,*items 捕获集合元素
  2. 类型验证:直接匹配 str(name)/int(age) 等类型
  3. 或模式"zip" | "tar" 匹配多选项
  4. 守卫条件if len(values)>3 实现复杂逻辑

⚠️ 注意:集合匹配忽略顺序,{1,2}{2,1} 视为相同模式

此特性显著简化了复杂数据结构的处理逻辑,使代码更声明式且易于维护。建议在数据处理、API响应解析等场景优先采用。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐