AI 大模型应用开发前置知识:Python 泛型编程全教程

前言

本教程是完整、体系化、具有一定深度 的 Python 泛型编程教程,覆盖所有语法、所有概念、所有高级特性、所有工程场景,无跳跃、无简化、无省略,完全满足大模型应用开发、框架封装、组件设计、架构演进的全部要求。

适用场景:

  • LangChain / LlamaIndex 二次开发

  • 大模型服务端架构

  • RAG 系统通用组件

  • 向量数据库封装

  • 企业级 Python 框架开发


目录

  1. 泛型编程的核心定义与设计思想

  2. 泛型的价值:为什么大模型开发必须用泛型

  3. 泛型基础:TypeVar 完全解析

  4. 泛型函数:定义、约束、多类型、嵌套

  5. 泛型类:单参数、多参数、继承、组合

  6. 泛型方法、类方法、静态方法

  7. 型变体系:不变、协变、逆变、协变逆变混用

  8. 泛型约束:bound、多类型约束、Protocol 约束

  9. 泛型与类型别名、TypedDict、Literal 结合

  10. 泛型与异步、生成器、异步生成器

  11. 泛型与 Callable、高阶函数、装饰器

  12. 高级泛型:TypeVarTuple、Unpack、ParamSpec

  13. 泛型与 Self、ClassVar、Instance 类型

  14. 泛型的抽象基类(ABC + Generic)

  15. 泛型在 mypy 下的严格检查规则

  16. 泛型常见错误、最佳实践、工程规范

  17. 大模型项目实战:泛型架构完整示例


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
相关推荐
MaoziShan1 小时前
CMU Subword Modeling | 10 Grammatical Properties
人工智能·语言模型·自然语言处理
shix .1 小时前
旅行网站控制台检测
开发语言·前端·javascript
小付同学呀1 小时前
C语言学习(四)——C语言变量、常量
c语言·开发语言
黑巧克力可减脂2 小时前
AI做心理咨询:当科技有温度,让治愈不缺席
人工智能·科技·语言模型·重构
倔强青铜三2 小时前
2026年Claude Code必备插件清单,第3个让我爱不释手
人工智能·ai编程·claude
艾莉丝努力练剑2 小时前
【Linux:文件】进程间通信
linux·运维·服务器·c语言·网络·c++·人工智能
MoonOutCloudBack2 小时前
VeRL 框架中的奖励 (reward) 与奖励模型:从 PPO 配置到实现细节
人工智能·深度学习·语言模型·自然语言处理
alfred_torres2 小时前
MedIA 2025 | TopoTxR:拓扑学“外挂”加持,深度学习精准预测乳腺癌化疗响应
人工智能·深度学习·拓扑学
梦游钓鱼2 小时前
C++指针深度解析:核心概念与工业级实践
开发语言·c++