理解

Annotated 是 Python 类型注解的增强机制。

常见写法:

Annotated[A, B]

Annotated 本身只负责关联类型和元数据,并不主动执行数据校验。

Python 的框架或第三方库(例如 Pydantic、FastAPI)可以读取这些元数据,并根据自身实现执行校验、参数解析、文档生成等操作。

因此,Annotated 不依赖 BaseModel,也不局限于数据校验。

一句话总结:Annotated 负责描述规则,Pydantic、FastAPI 等框架负责解释和执行规则。

实践

# Pydantic之后使用
from typing import Annotated
from pydantic import BaseModel, Field

class Student(BaseModel):
    name: str
    age: Annotated[int, Field(gt=0, lt=100)]

stu = Student(name="张三", age=-10)


# Fastapi中使用

from typing import Annotated
from fastapi import FastAPI, Query

app = FastAPI()

@app.get("/student")
async def get_student(
    age: Annotated[int, Query(gt=0, lt=100)]
):
    return {"age": age}