Python中类型提示、typing及union
在 Python 中,自 3.5 起引入了 typing 模块,用来给代码“加注解”(type hints)。这些注解不会由解释器强制执行,但可以被静态检查工具(mypy、pyright、pylance 等)、IDE 和文档生成器利用,从而提高可读性、可维护性并尽早发现类型相关的 bug。
1. typing 模块的常见成员
| 名称 | 说明 | 3.9+ 内建语法糖 |
|---|---|---|
List, Dict, Tuple, Set, … |
泛型集合 | list, dict, tuple, set |
Optional[T] |
Union[T, None] 的简写 |
T | None |
Union[T1, T2, …] |
“或”类型 | T1 | T2 | … |
Callable[[Arg1Type, Arg2Type], ReturnType] |
函数/可调用对象 | - |
Any, NoReturn, Literal, Final, ClassVar, … |
其它辅助 | - |
基础容器类型提示
针对内置容器(列表、字典、元组等),typing 提供了泛型版本,用于指定容器内元素的类型:
from typing import List, Dict, Tuple, Set
# 列表:元素均为 int 类型
def sum_numbers(numbers: List[int]) -> int:
return sum(numbers)
# 字典:键为 str 类型,值为 int 类型
def count_words(freq: Dict[str, int]) -> int:
return sum(freq.values())
# 元组:固定长度和类型(第一个元素为 str,第二个为 int)
def user_info() -> Tuple[str, int]:
return ("Alice", 30)
# 集合:元素均为 float 类型
def unique_values(values: Set[float]) -> int:
return len(values)
2. Union 的两种写法
2.1 旧写法:typing.Union
from typing import Union
def add(x: Union[int, float]) -> Union[int, float]:
return x + 1
2.2 3.10+ 新语法:| 联合运算符(PEP 604)
# Python 3.10+
def add(x: int | float) -> int | float:
return x + 1
在 3.9 及更早版本里只能用
typing.Union;从 3.10 开始,|语法被正式纳入语言,不需要额外 import。
3. Optional[T] vs Union[T, None]
from typing import Optional
def find(key: str) -> Optional[str]:
...
等价于:
def find(key: str) -> str | None: # 3.10+
...
4. 典型示例
from typing import List, Dict, Callable
def process(
items: List[int],
transform: Callable[[int], str],
config: Dict[str, bool] | None = None, # 3.10+
) -> List[str]:
if config is None:
config = {}
return [transform(x) for x in items]
5. 运行时检查?NO!
类型注解在运行时被解释器忽略:
def foo(x: int) -> str:
return x # 运行正常,但 mypy 会报错
若需要运行时校验,可用第三方库(pydantic, typeguard, enforce 等)。
6. 迁移建议
- 3.8 及以下:继续使用
from typing import Union, List, Optional等。 - 3.9:可开始用内建
list,dict等,但Union仍需typing.Union或__future__导入。 - 3.10+:优先使用
|语法,减少typing的导入量。
7. 小结一句话
typing.Union(或 3.10 的|)用于表达“这个值可以是多种类型之一”;typing模块里的其它工具则帮助我们给函数、变量、类属性等添加更精确、可读且可被静态分析的类型注解。
浙公网安备 33010602011771号