一、糖味一句話
Python 3.10+ 的 match-case
把「類型 + 值 + 嵌套」一次性拆開,
可讀性 ×10,bug 數 ÷10,if-elif 可以安心退休了。
二、1 行示例 3 連發
# ① 值匹配
match status:case 200: msg = "ok"case 404: msg = "not found"case _: msg = "unknown"# ② 結構匹配 + 守衛
match data:case {"name": str(n), "age": int(a)} if a >= 18:print(f"Adult {n}")case {"name": n}: # 只關心 key,不關心類型print(f"Minor {n}")# ③ 序列匹配帶星號
match cmd:case ["copy", src, dst]:shutil.copy(src, dst)case ["move", *files, dst]:for f in files: shutil.move(f, dst)
三、真實場景:JSON API 響應秒解析
需求:根據返回體結構做不同處理。
import requests, sysresp = requests.get(sys.argv[1]).json()match resp:case {"status": "ok", "data": list(items)}:print("Got", len(items), "items")case {"status": "error", "message": str(msg)}:print("Error:", msg)case _:print("Unknown format")
無需層層 if "status" in resp and isinstance(...)
。
四、防踩坑小貼士
match
從上到下短路匹配,順序即優先級。- 用
_
作通配符,但別把它當變量再用,會覆蓋。 - 模式里的變量名會綁定到作用域,注意命名沖突。
- 低于 3.10 的環境無法使用,需回退到 if-elif。
記憶口令 :“match 拆結構,case 當分支;下劃線兜底,守衛加條件。”