Python 3.10+ 类型提示进阶:用Union与TypeGuard编写更健壮的代码
Python的类型提示系统正日趋成熟。从Python 3.10开始,|操作符和TypeGuard的引入,让我们能以更优雅、更安全的方式处理多种可能的类型。
传统方式的痛点
过去我们常常这样处理多种类型:
from typing import Union, List
def process_data(data: Union[int, List[int]]) -> int:
if isinstance(data, int):
return data * 2
else: # 只能是List[int]
return sum(data)
这种写法有两个问题:
Union[int, List[int]]的语法略显冗长- else分支的类型推断不够精确(仍显示为
Union类型)
Python 3.10+ 的现代写法
# 更简洁的联合类型语法
def process_data(data: int | list[int]) -> int:
if isinstance(data, int):
return data * 2
else: # 类型系统能识别出这里只能是list[int]
return sum(data)
但真正的突破在于TypeGuard——它让类型系统理解我们自定义的类型检查:
from typing import TypeGuard
def is_string_list(val: list) -> TypeGuard[list[str]]:
return all(isinstance(x, str) for x in val)
def process_strings(data: list[str] | list[int]):
if is_string_list(data):
# 这里IDE能准确推断data为list[str]
return [s.upper() for s in data] # 安全调用字符串方法
else:
return [x * 2 for x in data] # 推断为list[int]
核心价值
- 更精确的静态分析:TypeGuard让Pylance、PyCharm等工具能理解复杂的类型约束
- 运行时安全保障:将类型检查逻辑封装为可复用函数
- 代码自文档化:类型声明本身就是最好的文档
实战建议
- 在处理API响应、用户输入等动态数据时,优先使用TypeGuard进行类型验证
- 在团队协作中,建立共享的TypeGuard函数库
- 将复杂的类型约束(如“非空列表”“有效邮箱格式”)都封装为TypeGuard
Python的类型系统正从“可有可无的文档”转变为“可执行的开发约束”。合理运用这些新特性,能在保持Python灵活性的同时,显著提升代码的可靠性和可维护性。