Python typing 模块【全面指南】与【类型注解】一文详解!
Python typing 模块全面指南与类型注解详解
前言
Python 的 typing 模块是现代 Python 开发(尤其是大型项目)中不可或缺的神器。它能极大地提高代码的可读性,并配合 IDE(如 VS Code、PyCharm)和静态类型检查工具(如 mypy)进行类型检查,减少运行时 Bug。
以下内容整理了所有类型注解补全,并额外补充了其他高频常用类型,分为四大类进行详细说明,帮助你一次性全面掌握。
导入部分(已补全常用类型)
from typing import (
TYPE_CHECKING,
Literal,
Optional,
Callable,
Generator,
Dict,
List, # 补充:列表
Tuple, # 补充:元组
Set, # 补充:集合
Any,
Awaitable,
Union,
Iterable, # 补充:可迭代对象
Iterator, # 补充:迭代器
Sequence, # 补充:序列(更宽泛的列表/元组/字符串)
TypeVar, # 补充:泛型变量
Protocol, # 补充:协议(结构化类型/鸭子类型)
TypedDict, # 补充:类型化字典(固定键)
Final, # 补充:最终变量(不可重新赋值)
Annotated, # 补充:带元数据的类型(Python 3.9+)
cast, # 补充:类型转换工具(运行时不检查)
overload, # 补充:函数重载
)
注意:Python 3.9+ 后,内置容器(如
list,dict,tuple,set)可以直接小写使用,无需从typing导入。但为了兼容旧版本和统一风格,很多项目仍从typing导入。
第一类:基础容器与数据结构 (Basic Containers)
1. Dict[K, V]、List[T]、Tuple[... ]、Set[T]
- 用法:泛型容器,指定内部元素的类型。
- 场景:明确数据结构的内容,提高可读性和检查严谨性。
from typing import Dict, List, Tuple, Set
user_info: Dict[str, int] = {"age": 18, "id": 1001}
scores: List[float] = [98.5, 88.0, 100.0]
point: Tuple[int, int, int] = (10, 20, 30) # 定长定类型
flexible_tuple: Tuple[int, ...] = (1, 2, 3, 4) # 变长同类型(Python 3.11+ 更优雅)
unique_ids: Set[str] = {"id1", "id2"}
2. Any
- 用法:表示任意类型,类型检查器对此变量完全放行。
- 注意:慎用!相当于关闭类型检查,失去 typing 的意义。
from typing import Any
def print_anything(data: Any) -> None:
print(data) # 可以传任何类型
3. Sequence[T](补充)
- 含义:比 List 更宽泛,包括 list、tuple、str、bytes 等所有支持索引、len()、切片的序列。
- 优势:函数参数更通用,兼容性更好。
from typing import Sequence
def print_reverse(seq: Sequence[int]) -> None:
print(seq[::-1]) # 接受 list、tuple、range 等
第二类:逻辑控制与组合 (Logic & Composition)
4. Union[A, B, ...]
- 含义:联合类型,“A 或 B 或 …”。
- 新语法(Python 3.10+):直接用
A | B。
from typing import Union
def get_user(user_id: Union[int, str]) -> None: ...
# 等价于 Python 3.10+
# def get_user(user_id: int | str) -> None: ...
5. Optional[T]
- 含义:等价于
T | None,表示可以为 None。 - 常见场景:函数参数默认值为 None。
from typing import Optional
def greet(name: Optional[str] = None) -> None:
print(f"Hello, {name or 'Guest'}")
6. Literal['a', 'b', 42]
- 含义:字面量类型,变量值必须是指定的常量之一。
- 场景:模式选择、状态码、配置开关,非常适合代替枚举的轻量场景。
from typing import Literal
FileMode = Literal['r', 'w', 'a', 'rb']
def open_file(mode: FileMode) -> None: ...
第三类:函数、生成器与异步 (Functions & Async)
7. Callable[[Arg1, Arg2, ...], ReturnType]
- 含义:表示一个可调用对象(函数、lambda、类实例带 call)。
- 用法:常用于回调函数参数。
from typing import Callable
def calculate(a: int, b: int, op: Callable[[int, int], int]) -> int:
return op(a, b)
calculate(3, 4, lambda x, y: x * y)
8. Generator[YieldType, SendType, ReturnType]
- 含义:标注 yield 生成器的三种类型。
- YieldType:yield 出的值类型(最常用)。
- SendType:通过
.send()传入的值类型(常用 None)。 - ReturnType:生成器结束时的返回值(通常 None)。
from typing import Generator
def count_down(n: int) -> Generator[int, None, None]:
while n > 0:
yield n
n -= 1
9. Iterable[T] 与 Iterator[T](补充)
- Iterable:可被 for 循环遍历的对象。
- Iterator:支持 next() 的对象(通常是 Iterable 的迭代器)。
- 建议:参数只需遍历时用 Iterable 更宽松。
from typing import Iterable
def process_items(items: Iterable[str]) -> None:
for item in items:
print(item)
10. Awaitable[T]
- 含义:可以被
await的对象(通常是协程)。 - 场景:高级异步框架中传递任务。
from typing import Awaitable
async def run_task(task: Awaitable[int]) -> None:
result = await task
print(result)
第四类:特殊工具与高级用法 (Special Tools)
11. TYPE_CHECKING
- 含义:运行时为 False,类型检查时为 True。
- 核心用途:解决循环导入问题,只在静态检查时导入类。
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .models import User # 只在 mypy 检查时导入
def process_user(user: "User") -> None: ... # 字符串引用避免运行时导入
12. TypeVar、Generic(补充泛型)
- 用途:实现类型一致的泛型函数/类。
from typing import TypeVar, List
T = TypeVar('T')
def first_item(items: List[T]) -> T:
return items[0]
# 调用时自动推断:first_item([1, 2]) -> int
13. Final[T](补充)
- 含义:标记变量/属性不可重新赋值(类型检查器会报错)。
from typing import Final
API_KEY: Final[str] = "abc123"
# API_KEY = "new" # mypy 会报错
14. Annotated[T, ...](补充,Python 3.9+)
- 含义:为类型附加元数据,常用于第三方库(如 pydantic、fastapi)的验证。
from typing import Annotated
PositiveInt = Annotated[int, lambda x: x > 0]
def set_age(age: PositiveInt) -> None: ...
15. TypedDict(补充)
- 含义:为字典指定固定键和对应类型(结构化 dict)。
from typing import TypedDict
class Movie(TypedDict):
title: str
year: int
movie: Movie = {"title": "Inception", "year": 2010}
总结速查表 (Cheatsheet)
| 类型注解 | 简单解释 | 典型场景 |
|---|---|---|
Dict[K, V] |
字典,指定键值类型 | 配置、JSON 数据 |
List[T] |
列表 | 集合数据 |
Tuple[A, B, ...] |
定长元组 | 坐标、固定字段 |
Set[T] |
集合 | 去重 ID |
Sequence[T] |
通用序列(list/tuple/str 等) | 参数只需索引访问 |
Any |
任意类型(慎用) | 动态数据、第三方库回调 |
Union[A, B] 或 A | B |
多选一 | ID 可为 int 或 str |
Optional[T] |
T 或 None | 可选参数、可能缺失字段 |
Literal['a', 42] |
固定字面值 | 模式、状态码 |
Callable[[...], R] |
函数/回调 | 高阶函数、策略模式 |
Generator[Y, S, R] |
生成器 | yield 迭代器 |
Iterable[T] |
可遍历对象 | for 循环参数 |
Awaitable[T] |
可 await 的协程 | 异步任务调度 |
TYPE_CHECKING |
类型检查开关 | 解决循环导入 |
TypeVar('T') |
泛型占位符 | 通用函数/类 |
Final[T] |
不可变常量 | 配置常量、魔法值 |
Annotated[T, ...] |
带元数据类型 | 验证、依赖注入 |
TypedDict |
固定键类型的字典 | API 返回结构、配置 |

浙公网安备 33010602011771号