Python 3.10 引入了革命性的结构模式匹配(match-case),为Python开发者带来了更强大、更优雅的条件处理工具。本文将深入探索这一新特性,助你提升代码可读性和表达力。
为什么需要 match-case?
在 Python 3.10 之前,处理多条件分支通常有:冗长的 if-elif-else 链、使用字典模拟 switch-case、嵌套条件导致的"箭头反模式"。
这些方法在复杂场景下往往导致代码可读性差、维护困难。match-case 的引入解决了这些问题,提供了更声明式的条件处理方式。
可能有人会简单地认为这不就是
switch-case
吗?
注意:match-case
并非传统语言中的 switch-case,它不仅能进行值匹配,还支持类型匹配、解构匹配、嵌套匹配等“结构化模式匹配”能力,语义更接近 Haskell/Scala 的模式匹配。
基础语法:第一个 match-case
def http_status(status):
match status:
case 200:
return "OK"
case 404:
return "Not Found"
case 500:
return "Internal Server Error"
case _: # _是通配符,表示“任意其他情况”
return "Unknown Status"
print(http_status(200)) # 输出: OK
print(http_status(404)) # 输出: Not Found
print(http_status(418)) # 输出: Unknown Status
核心功能
1. 多值匹配(OR模式)
def handle_command(cmd):
match cmd.split():
case ["quit"] | ["exit"] | ["q"]:
print("Exiting program...")
case ["load", filename]:
print(f"Loading {
filename}...")
case ["save", filename]:
print(f"Saving {
filename}...")
case _:
print("Unknown command")
handle_command("quit") # Exiting program...
handle_command("load data.txt") # Loading data.txt...
2. 通配符与变量绑定
def process_data(data):
match data:
case []:
print("Empty list")
case [x]:
print(f"Single element: {
x}")
case [x, y]:
print(f"Two elements: {
x} and {
y}")
case [first, *rest]:
print(f"First: {
first}, Rest: {
rest}")
process_data([1, 2, 3, 4])
# 输出: First: 1, Rest: [2, 3, 4]
3. 类型匹配
类匹配需预先定义 __match_args__
(或使用 dataclass
)
def handle_value(value