前言
本教程是完整、体系化、具有一定深度 的 Python 泛型编程教程,覆盖所有语法、所有概念、所有高级特性、所有工程场景,无跳跃、无简化、无省略,完全满足大模型应用开发、框架封装、组件设计、架构演进的全部要求。
适用场景:
-
LangChain / LlamaIndex 二次开发
-
大模型服务端架构
-
RAG 系统通用组件
-
向量数据库封装
-
企业级 Python 框架开发
目录
-
泛型编程的核心定义与设计思想
-
泛型的价值:为什么大模型开发必须用泛型
-
泛型基础:TypeVar 完全解析
-
泛型函数:定义、约束、多类型、嵌套
-
泛型类:单参数、多参数、继承、组合
-
泛型方法、类方法、静态方法
-
型变体系:不变、协变、逆变、协变逆变混用
-
泛型约束:bound、多类型约束、Protocol 约束
-
泛型与类型别名、TypedDict、Literal 结合
-
泛型与异步、生成器、异步生成器
-
泛型与 Callable、高阶函数、装饰器
-
高级泛型:TypeVarTuple、Unpack、ParamSpec
-
泛型与 Self、ClassVar、Instance 类型
-
泛型的抽象基类(ABC + Generic)
-
泛型在 mypy 下的严格检查规则
-
泛型常见错误、最佳实践、工程规范
-
大模型项目实战:泛型架构完整示例
1 泛型编程的核心定义与设计思想
1.1 什么是泛型
泛型(Generic Programming) 是一种参数化类型 机制,允许在定义类、函数、接口时使用类型占位符,在使用时再指定具体类型,从而实现:
-
代码高度复用
-
编译期类型安全
-
不依赖 Any
-
架构可扩展
1.2 泛型解决的本质问题
-
不使用泛型:组件只能写死类型 or 使用 Any(不安全)
-
使用泛型:一套代码支持任意类型,同时保持类型检查
1.3 泛型的核心组成
-
类型变量(TypeVar):占位符
-
泛型基类(Generic):声明泛型类
-
泛型函数/泛型类:具体逻辑
-
型变(Covariance/Contravariance):类型兼容规则
-
约束(Constraint):限制类型范围
2 泛型的价值:为什么大模型开发必须用泛型
大模型项目中高频需要:
-
通用向量存储(支持任意 Embedding 结构)
-
通用文档处理器(支持 TextDoc、ImageDoc、AudioDoc)
-
通用缓存(支持任意返回值)
-
通用回调系统(支持任意消息格式)
-
通用流式生成器(支持 str、bytes、chunk)
泛型 = 大模型工程化的基石
3 泛型基础:TypeVar 完全解析
3.1 TypeVar 是什么
类型变量,是泛型的占位符,用于在定义时"先占一个类型位置"。
3.2 标准定义方式
python
from typing import TypeVar
T = TypeVar("T")
规则:引号内名称必须与变量名一致
3.3 TypeVar 的三种形态
3.3.1 无约束(任意类型)
python
T = TypeVar("T")
可代表:int、str、list、object、自定义类
3.3.2 多类型约束(只能是指定类型之一)
python
NumT = TypeVar("NumT", int, float)
只能是 int 或 float
3.3.3 上限约束 bound(必须是某类及其子类)
python
class BaseDocument:
pass
DocT = TypeVar("DocT", bound=BaseDocument)
AI 项目最常用
3.4 TypeVar 命名规范
-
通用:T, U, V
-
业务:DocT, EmbT, ModelT, ConfigT
-
框架级:_T, _U(内部使用)
4 泛型函数
4.1 最简单泛型函数
python
def identity(value: T) -> T:
return value
4.2 容器类型泛型函数
python
def first(items: list[T]) -> T:
return items[0]
4.3 多类型泛型函数
python
U = TypeVar("U")
def zip_pair(a: T, b: U) -> tuple[T, U]:
return a, b
4.4 带默认值的泛型函数
python
def get_item(items: list[T], default: T | None = None) -> T | None:
return items[0] if items else default
4.5 嵌套容器泛型函数
python
def flatten(matrix: list[list[T]]) -> list[T]:
return [x for row in matrix for x in row]
4.6 带约束的泛型函数
python
def add(a: NumT, b: NumT) -> NumT:
return a + b
5 泛型类
5.1 单类型泛型类
python
from typing import Generic
class Store(Generic[T]):
def __init__(self) -> None:
self.items: list[T] = []
def add(self, item: T) -> None:
self.items.append(item)
def get_all(self) -> list[T]:
return self.items
5.2 使用方式
python
s = Store[str]()
s.add("hello")
5.3 多类型泛型类
python
K = TypeVar("K")
V = TypeVar("V")
class KVStore(Generic[K, V]):
def __init__(self) -> None:
self.data: dict[K, V] = {}
def set(self, key: K, value: V) -> None:
self.data[key] = value
def get(self, key: K) -> V:
return self.data[key]
5.4 泛型类的继承
5.4.1 继承并固定类型
python
class VectorStore(Store[list[float]]):
def search(self, query: list[float]) -> list[float]:
return self.get_all()[0]
5.4.2 子类继续保持泛型
python
class BaseRepo(Generic[T]):
def save(self, data: T) -> None: ...
class LLMRepo(BaseRepo[T]):
def query(self) -> T: ...
6 泛型方法、类方法、静态方法
6.1 泛型方法
python
class Service:
def process(self, data: T) -> T:
return data
6.2 类方法 + 泛型
python
class Service:
@classmethod
def create(cls: type[T]) -> T:
return cls()
6.3 静态方法 + 泛型
python
class Service:
@staticmethod
def parse(data: T) -> T:
return data
7 型变体系:不变、协变、逆变
这是泛型最核心、最系统、最容易被忽略的高级知识点
7.1 型变定义
-
不变(Invariant) :默认。
Generic[T]与Generic[S]无关 -
协变(Covariant) :若 S 是 T 子类,则
C[S]是C[T]子类 -
逆变(Contravariant) :若 S 是 T 子类,则
C[S]是C[T]父类
7.2 协变定义
python
T_co = TypeVar("T_co", covariant=True)
class Producer(Generic[T_co]):
def get(self) -> T_co: ...
协变 = 输出/返回/读取
7.3 逆变定义
python
T_contra = TypeVar("T_contra", contravariant=True)
class Consumer(Generic[T_contra]):
def consume(self, value: T_contra) -> None: ...
逆变 = 输入/参数/写入
7.4 型变总结(必须背会)
-
协变:产出
-
逆变:消费
-
不变:既产出又消费
8 泛型约束
8.1 bound 上限约束
python
class BaseModel: ...
ModelT = TypeVar("ModelT", bound=BaseModel)
8.2 多类型约束
python
NumT = TypeVar("NumT", int, float)
8.3 Protocol 约束(接口式泛型)
python
class Encodable(Protocol):
def encode(self) -> str: ...
T = TypeVar("T", bound=Encodable)
9 泛型与类型系统高级组合
9.1 泛型 + TypedDict
python
class Doc(TypedDict):
content: str
DocT = TypeVar("DocT", bound=Doc)
class DocStore(Generic[DocT]): ...
9.2 泛型 + Literal
python
Mode = Literal["sync", "async"]
T = TypeVar("T")
class Runner(Generic[T, Mode]): ...
9.3 泛型 + 类型别名
python
Embedding = list[float]
EmbT = TypeVar("EmbT", bound=Embedding)
10 泛型与异步、生成器
10.1 泛型生成器
python
def stream(items: list[T]) -> Generator[T, None, None]:
yield from items
10.2 泛型异步生成器
python
async def async_stream(items: list[T]) -> AsyncGenerator[T, None]:
for item in items:
yield item
10.3 泛型异步函数
python
async def async_get(key: str) -> T: ...
11 泛型与 Callable、高阶函数
python
class Event(Generic[T]):
def on(self, handler: Callable[[T], None]) -> None: ...
def emit(self, value: T) -> None: ...
12 高级泛型:TypeVarTuple、Unpack、ParamSpec
12.1 TypeVarTuple(变长类型)
python
from typing import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
class TupleStore(Generic[Unpack[Ts]]):
def set(self, *values: Unpack[Ts]) -> None: ...
12.2 ParamSpec(函数参数泛型)
python
from typing import ParamSpec
P = ParamSpec("P")
def decorator(func: Callable[P, T]) -> Callable[P, T]:
def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
return func(*args, **kwargs)
return wrapper
13 泛型与 Self、ClassVar
13.1 Self 类型
python
from typing import Self
class Builder(Generic[T]):
def build(self) -> Self:
return self
13.2 ClassVar + 泛型
python
class BaseService(Generic[T]):
registry: ClassVar[dict[str, T]] = {}
14 泛型 + 抽象基类 ABC
python
from abc import ABC, abstractmethod
class BaseVectorDB(Generic[T], ABC):
@abstractmethod
def add(self, vec: T) -> None: ...
@abstractmethod
def query(self, q: T) -> list[T]: ...
15 mypy 严格检查规则
Plain
mypy --strict --allow-generics
作用:
-
强制泛型参数
-
强制型变检查
-
强制约束检查
16 泛型常见错误与最佳实践
16.1 常见错误
-
TypeVar 名称不一致
-
忘记继承 Generic
-
协变逆变颠倒
-
未指定泛型参数
-
使用 Any 替代泛型
16.2 最佳实践
-
优先使用 bound
-
框架必须使用型变
-
组件必须使用泛型
-
禁止 Any
17 大模型实战:完整泛型架构
python
Embedding = list[float]
class BaseDocument(ABC):
content: str
embedding: Embedding
DocT = TypeVar("DocT", bound=BaseDocument)
EmbT = TypeVar("EmbT", bound=Embedding)
class BaseVectorStore(Generic[EmbT, DocT], ABC):
def add_document(self, doc: DocT) -> None: ...
def search(self, query: EmbT) -> list[DocT]: ...
class RAGService(Generic[DocT]):
def __init__(self, store: BaseVectorStore[EmbT, DocT]):
self.store = store