如何使用新的 type 语法简化泛型模型?
解读
“新的 type 语法”在国内面试语境里通常指 Python 3.9+ 引入的「内置泛型」写法(list[str] 代替 typing.List[str])以及 3.12 进一步简化的「泛型类型别名」与「TypeVar 默认值」。
FastAPI 重度依赖 Pydantic,而 Pydantic v2 已全面拥抱 PEP 563/585/695,因此面试官想确认两点:
- 你是否能把传统 typing 模板代码压缩成更短、可读性更高的新语法;
- 你是否知道新语法在 FastAPI 的序列化、校验、OpenAPI 生成链路里会不会踩坑。
回答时务必给出“迁移前 vs 迁移后”的代码对比,并指出边界场景(如 TypeVar 有界、协变、逆变)在 FastAPI 中的实际表现。
知识点
- PEP 585:内置泛型,如 list[int]、dict[str, float] 可直接使用,无需从 typing 导入。
- PEP 604:联合类型写成
str | int,无需Union。 - PEP 695(Python 3.12):
type Point[T] = tuple[T, T],把 TypeVar 声明与别名合二为一。 - Pydantic v2 的 GenericModel 已废弃,统一用
BaseModel配合typing.TypeVar或 3.12 的新语法即可。 - FastAPI 0.100+ 同步升级了 Starlette 与 Pydantic,保证新语法生成的 OpenAPI 3.1 文档字段类型正确。
- 边界注意:
- 有界 TypeVar(
TypeVar("T", bound=BaseModel))在新语法里仍须显式声明; - 逆变/协变(covariant=True)在 FastAPI 响应模型里一般无实际意义,可忽略;
- 3.9 以下环境必须
from __future__ import annotations才能放心写 list[str],否则运行期抛 TypeError。
- 有界 TypeVar(
答案
传统写法(Python 3.8 及早期项目常见):
from typing import TypeVar, Generic, List
from pydantic import BaseModel
from fastapi import FastAPI
T = TypeVar("T")
class Paginated(Generic[T]):
total: int
items: List[T]
class User(BaseModel):
id: int
name: str
@app.get("/users", response_model=Paginated[User])
async def list_users():
...
新语法(Python 3.9+ 推荐,3.12 更简洁):
from pydantic import BaseModel
from fastapi import FastAPI
type Paginated[T] = dict[str, T | int] # 3.12 一行搞定别名
class User(BaseModel):
id: int
name: str
@app.get("/users", response_model=dict[str, User | int]) # 直接内联
async def list_users():
...
如果仍需复用泛型结构,可保留 BaseModel 但用内置泛型:
class Paginated[T](BaseModel):
total: int
items: list[T] # PEP 585
迁移收益:
- 代码量减少 30 % 以上;
- 无需额外导入 typing 成员,降低循环导入风险;
- OpenAPI 文档自动识别 list[str]、str | int,前端 TypeScript 生成器直接产出正确数组/联合类型。
拓展思考
- 老项目兼容:在
pyproject.toml里把 target-version 设为 3.9,配合ruff/pyupgrade可一键把 List→list、Union→|。 - 性能:PEP 585 内置泛型在 CPython 层走 slot,模型构建耗时降低 5 % 左右,压测 QPS 提升可忽略,但内存占用略降。
- 泛型嵌套:FastAPI 的
response_model=list[Paginated[User]]完全合法,OpenAPI 会生成array of object,但 Swagger UI 目前对 3.1 联合类型渲染仍不完美,需要 Redoc 查看。 - 前向引用:若模型相互引用,务必保持
from __future__ import annotations,否则 3.9 也会抛NameError。 - 面试加分项:可以主动提到“我们内部用 3.12 的
type别名做领域层防腐,FastAPI 层只依赖别名,不直接 import 领域模型,从而把 ORM、Pydantic 与业务核心完全解耦”。