11 · Protocol、泛型与 overload
学完这章,你能用
Protocol描述结构化接口、用泛型保留元素类型、读懂协变/不变导致的报错,并正确使用@overload与TypeIs。
本章目标
- 能区分名义子类型与结构化子类型,用
Protocol定义「只看行为」的接口 - 能说明
runtime_checkable的isinstance只检查名字、不检查签名 - 能用
TypeVar/PEP 695 写泛型函数与泛型类,知道泛型在运行时被擦除 - 能解释协变、不变与逆变,知道
list为什么不能当list[object]用 - 能写
@overload并知道运行时只有实现、get_overloads能取回桩 - 能区分
TypeGuard与 3.13 的TypeIs,并正确使用Self/Never/ParamSpec
前置知识
- 第 08 章(类、MRO、属性查找)、第 10 章(类型注解、mypy、
TypedDict) - 任意语言里的接口/泛型/重载经验(Go interface、Java 泛型、C++ 模板)
从你熟悉的语言出发
| 概念 | Go | Java | C++ | Python |
|---|---|---|---|---|
| 接口匹配 | 隐式 interface | 显式 implements |
concept(C++20) | Protocol 结构化匹配 |
| 泛型 | 1.18+ 类型参数 | 泛型擦除 | 模板单态化 | TypeVar/PEP 695,运行时擦除 |
| 重载 | 不支持 | 编译期重载 | 编译期重载 | @overload 仅静态 |
| 可变性 | 切片协变 | 数组协变(有坑) | 模板不变 | list 不变、Sequence 协变 |
| 运行时分派 | interface 表 | 虚方法表 | 虚表/模板 | 描述符 + MRO |
| 空接口 | any |
Object |
void* |
object、Any |
类比一:Protocol 像 Go 的隐式 interface,但检查发生在开发期。 Go 的 io.Reader 不要求类型声明实现它,只要有 Read 方法就满足;Python 的 Protocol 同样只看结构,但匹配由 mypy 完成,运行时不会自动生成接口表。
类比二:泛型像「带类型参数的模板签名」,但运行时被擦除。 C++ 模板会为每组类型生成代码;Python 的 Box[int] 和 Box[str] 在运行时是同一个类,类型参数只存在于注解和 __orig_class__ 这类元数据里。
正文
11.1 结构化子类型与 Protocol
class Shape(Protocol):
def area(self) -> float: ...任何有 area(self) -> float 的类都满足 Shape,不需要继承:
class Circle:
def area(self) -> float:
return 3.14
def total_area(shapes: list[Shape]) -> float:
return sum(shape.area() for shape in shapes)
total_area([Circle()]) # mypy 通过这和 Go 的隐式 interface 一致,也解释了为什么标准库用 Sized/Iterable/Hashable 这类 Protocol 描述能力,而不是要求继承某个基类。与名义子类型(Java implements)相比,结构匹配更灵活,但也更容易「碰巧满足」——方法名对了,语义未必对。
11.2 runtime_checkable 的边界
@runtime_checkable
class Shape(Protocol):
def area(self) -> float: ...isinstance(obj, Shape) 在运行时逐个检查属性是否存在,不检查:
- 属性是不是可调用;
- 方法签名(参数个数、类型、返回类型);
- 语义是否正确。
所以一个 area = 3.0 的类也能通过 isinstance,直到调用 obj.area() 才抛 TypeError。Protocol 的运行时检查只是「形状探测」,不是完整校验;需要严格校验时,自己写 isinstance + 字段检查(第 10 章)。
11.3 TypeVar:约束与上界
T = TypeVar("T")
S = TypeVar("S", bound=Shape)
N = TypeVar("N", int, float)
def first(items: Sequence[T]) -> T: ...
def area_of(shape: S) -> float: ...
def add(a: N, b: N) -> N: ...T无约束:调用时由实参推断。S有上界:只能接受Shape的子类型,函数体可调用shape.area()。N有约束:只能取列出的类型之一,且所有位置必须一致;add(1, 2.0)会被拒绝(推断不出唯一N)。
泛型函数在运行时没有额外开销:first 的字节码和普通函数一样,类型参数不参与执行。它的价值是让调用方保留元素类型,而不是返回 Any。
11.4 协变、不变与逆变
| 容器/接口 | 可变性 | 例子 |
|---|---|---|
list[T] |
不变 | list[int] 不是 list[object] |
Sequence[T] |
协变 | list[int] 可以当 Sequence[object] |
Iterable[T] |
协变 | 只读迭代 |
Callable[[T], R] |
参数逆变、返回协变 | 回调 |
dict[K, V] |
键值都不变 | 可写 |
为什么 list 不变:如果 list[int] 能当 list[object],就能往里面塞字符串,破坏原列表的元素类型。Sequence 只读,扩大元素类型不会引入写入,所以可以协变。
修法通常是收窄参数类型:需要读就用 Sequence[T]/Iterable[T],需要写才用 list[T]。这也是「参数尽量宽、返回尽量窄」原则的类型版本。
11.5 PEP 695 语法
Python 3.12 起可以把类型参数写在类/函数/别名上:
class Box[T]:
def __init__(self, value: T) -> None:
self.value = value
def first[T](items: Sequence[T]) -> T:
return items[0]
type Pair[T] = tuple[T, T]旧式写法仍然有效:
T = TypeVar("T")
class LegacyBox(Generic[T]): ...两者在运行时都擦除为普通类/函数。PEP 695 的好处是作用域清晰(类型参数不会泄漏到模块)、不用重复写 TypeVar 名字,也能写 class Box[T: Shape] 这样的上界。3.12 之前的项目只能使用旧式写法;跨版本库可以用 typing_extensions 的 TypeVar 兼容(本章不引入额外依赖)。
11.6 @overload
@overload
def parse(value: int) -> int: ...
@overload
def parse(value: str) -> str: ...
def parse(value: int | str) -> int | str:
if isinstance(value, int):
return value
return value.upper()规则:
@overload桩只写签名,函数体是...。- 最后一个同名函数是实现,必须有函数体;运行时只执行它。
- 实现签名必须能接受所有桩的参数(通常用联合类型)。
- 检查器按顺序匹配桩;
@overload的函数体不会被检查器执行。 typing.get_overloads(parse)能在运行时取回桩函数,主要用于框架/文档。
.pyi 存根是同一思路的极端形式:只保留接口,不保留实现,供库作者给无类型代码补注解。最小用法是「一个 .pyi 对应一个 .py」,不需要把所有内部实现都写进去。
11.7 Self、Never 与 ParamSpec
from typing import Never, Self
class Builder:
def add(self, value: int) -> Self:
...
return self
def fail(message: str) -> Never:
raise RuntimeError(message)Self表示「当前类」,子类调用时返回子类类型;比写死-> Builder更准确。Never表示「不会正常返回」,适合raise/sys.exit的返回类型。ParamSpec保留被装饰函数的参数签名:
from collections.abc import Callable
from typing import ParamSpec, TypeVar
P = ParamSpec("P")
R = TypeVar("R")
def logged(fn: Callable[P, R]) -> Callable[P, R]:
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
return fn(*args, **kwargs)
return wrapperTypeVarTuple/Unpack(PEP 646)用于「任意长度的类型参数」,典型是 tuple[*Ts];日常业务代码很少需要,遇到再查。
11.8 TypeGuard 与 TypeIs
两者都用于自定义收窄,区别在否定分支:
def is_str_list(value: int | list[str]) -> TypeGuard[list[str]]:
return isinstance(value, list)
def use(value: int | list[str]) -> int:
if not is_str_list(value):
return value + 1 # TypeGuard:value 仍是 int | list[str],mypy 报错
return len(value)把 TypeGuard 换成 3.13 的 TypeIs,else/否定分支会收窄为 int,value + 1 通过。TypeGuard 的优点是 3.10+ 可用、可以对任意条件做收窄(包括不严格的);TypeIs 要求收窄目标确实是原类型的子类型,更安全但不能表达「部分重叠」。
11.9 泛型与 Protocol 的组合
Protocol 本身可以带类型参数:
class Repository[T](Protocol):
def get(self, key: str) -> T | None: ...
def put(self, key: str, value: T) -> None: ...实现类 MemoryRepo[T] 只需结构匹配;测试里可以注入 FakeRepo,不需要继承。Protocol + 泛型是「依赖倒置」在类型层面的表达:调用方依赖能力,不依赖具体类。
报错现场
真实 mypy --strict 输出(mypy 2.4.1,文件见 examples/11-protocols-generics-overloads/06-variance/):
variance_case.py:13: error: Argument 1 to "takes_object_list" has incompatible type "list[int]"; expected "list[object]" [arg-type]
variance_case.py:13: note: "list" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance
variance_case.py:13: note: Consider using "Sequence" instead, which is covariant
Found 1 error in 1 file (checked 1 source file)逐行读:
list[int]是实参类型,list[object]是形参类型;list不变,所以不兼容。- 第二条 note 直接给出原因与文档链接。
- 第三条 note 给出修法:改用
Sequence(协变)。
修法:
from collections.abc import Sequence
def takes_object_sequence(values: Sequence[object]) -> int:
return len(values)
takes_object_sequence([1, 2, 3]) # 通过运行时两版都能跑:Python 不检查泛型参数,len([1,2,3]) 与元素类型无关。这正是「静态检查拦住一类设计错误,运行时不会」的例子。
反直觉差异:Protocol 的 isinstance 不比签名,泛型在运行时被擦除
你的直觉:isinstance(obj, Shape) 应该像 Java 的 instanceof 一样,确认对象真的实现了接口;Box[int] 和 Box[str] 应该是不同的类。
实际行为:
runtime_checkable的isinstance只检查属性名。Fake的area是浮点数,isinstance(fake, Shape)仍为真,调用时才TypeError。- 泛型被擦除。
type(Box[int](1)) is Box为真;Box[int]与Box[str]是同一个运行时类,只有显式下标实例化才留下__orig_class__。 @overload的实现签名不参与调用匹配。运行时parse(1.5)直接进入实现,检查器才会拦。
为什么这样设计:Python 要在不改变运行时对象模型的前提下支持渐进类型。Protocol 若做完整签名校验,需要运行时反射每个方法的注解,成本高且不可靠(注解可能被字符串化);泛型若具体化,会破坏「一个类一份实现」的简单模型。把严格性放在静态检查器,是性能与兼容性的折中。
正确写法:
- 需要运行时校验时,写显式
isinstance/字段检查,不依赖Protocol的isinstance。 - 泛型只用于静态约束;运行时需要类型信息时显式传
type或工厂。 @overload只用于类型;运行时分支自己用isinstance保证正确。
性能与复杂度
| 操作 | 实测(3.12.9 / macOS arm64) | 说明 |
|---|---|---|
泛型函数调用 first(data) |
32.1 ns | 与普通函数一致,类型参数零开销 |
直接下标 data[0] |
17.6 ns | 差值是函数调用帧 |
isinstance(obj, Circle) |
22.1 ns | 普通类检查 |
isinstance(obj, Shape)(runtime_checkable) |
241.7 ns | 逐属性探测,约 10 倍 |
泛型在运行时没有额外成本:TypeVar/PEP 695 只影响检查器,字节码与普通函数相同。真正有成本的是 runtime_checkable 的 isinstance:它要遍历协议成员并做 hasattr,不适合放在热路径;需要高频判断时用显式标记(如 isinstance 具体基类或 Enum)。
示例索引
| 目录 | 演示什么 | 预期看到 |
|---|---|---|
examples/11-protocols-generics-overloads/01-protocol-duck-typing/ |
结构化匹配 + runtime_checkable 只查名字 |
fake isinstance: True、'float' object is not callable |
examples/11-protocols-generics-overloads/02-generic-preserves-type/ |
泛型保留类型、运行时擦除 | first type: int、instance class: Box、__orig_class__ |
examples/11-protocols-generics-overloads/03-overload-signatures/ |
@overload 桩与实现 |
overloads: 2、float error: |
examples/11-protocols-generics-overloads/04-pep695-syntax/ |
PEP 695 vs 旧式泛型 | 两种 Box[int]、Pair[int] |
examples/11-protocols-generics-overloads/05-typeis-narrowing/ |
TypeGuard vs TypeIs |
typeguard error:、typeis success: True |
examples/11-protocols-generics-overloads/06-variance/ |
list 不变、Sequence 协变 |
[arg-type]、is invariant |
练习题
- 用
Protocol定义Shape,实现Circle/Rectangle与total_area。见exercises/11/01-protocol-area/。 - 用 PEP 695 实现
first[T](items: Sequence[T]) -> T,空序列抛ValueError。见exercises/11/02-generic-first/。 - 为
format_value写两个@overload(int/str)。见exercises/11/03-overload-format/。 - 用 PEP 695 实现
Box[T]与map[U]。见exercises/11/04-pep695-box/。 - 实现
total_length(values: Sequence[Sized]) -> int,接收list[str]/list[bytes]/list[tuple]。见exercises/11/05-sequence-sized/。
- 两个类不继承
Shape,只要方法匹配即可;total_area参数用Sequence[Shape]。 if not items: raise ValueError(...),否则return items[0];PEP 695 的[T]写在函数名后。- 两个
@overload桩 + 一个int | str实现;实现里用isinstance分支。 map用def map[U](self, fn: Callable[[T], U]) -> Box[U],返回Box(fn(self.value))。Sequence[Sized]既利用Sequence协变,又用Sized结构匹配;sum(len(v) for v in values)。
章末自检
- 结构化子类型与名义子类型有什么区别?
Protocol属于哪一种? runtime_checkable的isinstance检查什么、不检查什么?TypeVar的约束(constraints)与上界(bound)有什么区别?list[int]为什么不能赋给list[object]?怎么修?- PEP 695 的
class Box[T]与旧式Generic[T]在运行时有什么不同? @overload的桩和实现,运行时执行哪一个?get_overloads有什么用?TypeGuard与TypeIs在否定分支上有什么区别?Self/Never/ParamSpec各解决什么问题?
- 结构化看方法集合,名义看显式继承/实现;
Protocol是结构化。 - 检查属性名是否存在;不检查可调用性、签名、语义。
- 约束是枚举允许的类型且要求一致;上界是某个类型的子类型。
list可变,允许协变会破坏元素类型;改用Sequence/Iterable。- 运行时都擦除为普通类;PEP 695 只是语法/作用域更好,
Box[int]仍是同一个类。 - 只执行实现;
get_overloads取回桩,供框架/文档使用。 TypeGuard只收窄为真的分支;TypeIs在假分支收窄为排除后的类型。Self保留子类返回类型;Never表示不返回;ParamSpec保留被装饰函数的参数签名。
延伸阅读
- PEP 544 Protocols: Structural subtyping (static duck typing)
- PEP 483 / PEP 484 Type Hints
- PEP 585 Type Hinting Generics In Standard Collections
- PEP 604 Allow writing union types as
X | Y - PEP 646 Variadic Generics
- PEP 647 User-Defined Type Guards
- PEP 673 Self Type
- PEP 695 Type Parameter Syntax
- PEP 742 TypeIs
- mypy 文档:Protocols and structural subtyping、Generics、Variance of generic types、Function overloading