← 中文资源

简体中文版本

match 语句按结构拆解数据形状

match 语句按结构拆解字典与序列:字面量键匹配、捕获变量绑定载荷、guard 过滤形状放不过的值,一个 case 阶梯替代层层嵌套的 if 判断。

阅读英文原文

实现说明

match 语句按结构拆解数据形状可以归结为函数 handle_event、bounds。 这个文件只在 for event in [ 里循环。

使用要点

  • 把 handle_event 当作 API:导入它,其余代码可以忽略。

常见问题

需要安装第三方包吗?

不需要。只使用语言和平台的内建 API,粘贴进项目即可使用,无需安装任何东西。 文件在加载时定义 handle_event、bounds。

入口签名:def handle_event(event)

核心语句

def bounds(reading):
    match reading:
        case [low, high] if low <= high:
            return f"range {low}..{high}"
        case [single]:
            return f"single point {single}"
        case []:
            return "no readings"
        case _:
            return f"unexpected shape of {len(reading)} values"

代码示例

def handle_event(event):
    match event:
        case {"type": "deploy", "service": service, "env": "prod"}:
            return f"deploying {service} to prod"
        case {"type": "scale", "service": service, "replicas": n} if n > 0:
            return f"scaling {service} to {n} replicas"
        case {"type": kind, **rest}:
            return f"unhandled type {kind}: {sorted(rest)}"
        case _:
            return "malformed event, missing type"


def bounds(reading):
    match reading:
        case [low, high] if low <= high:
            return f"range {low}..{high}"
        case [single]:
            return f"single point {single}"
        case []:
            return "no readings"
        case _:
            return f"unexpected shape of {len(reading)} values"


for event in [
    {"type": "deploy", "service": "billing", "env": "prod"},
    {"type": "scale", "service": "auth", "replicas": 5},
    {"type": "scale", "service": "auth", "replicas": 0},  # the guard rejects it
    {"type": "ping"},
]:
    print(handle_event(event))

for reading in [[18, 24], [7], [], [1, 2, 3]]:
    print(bounds(reading))