跳转到内容

Pydantic 验证

CI Coverage
pypi CondaForge downloads
license llms.txt

文档版本:v2.12.1

Pydantic 是应用最广泛的 Python 数据验证库。

Pydantic 快速且可扩展,能与您的 linter/IDE/大脑 完美协作。用纯粹、规范的 Python 3.9+ 定义数据应有的格式,然后用 Pydantic 进行验证。

使用 Pydantic Logfire 监控 Pydantic 🔥

Pydantic Logfire 是一款应用程序监控工具,它像 Pydantic 本身一样简单易用且功能强大。

Logfire 集成了许多流行的 Python 库,包括 FastAPI、OpenAI 和 Pydantic 本身,因此您可以使用 Logfire 监控 Pydantic 验证,并了解某些输入验证失败的原因。

使用 Logfire 监控 Pydantic
from datetime import datetime

import logfire

from pydantic import BaseModel

logfire.configure()
logfire.instrument_pydantic()  # (1)!


class Delivery(BaseModel):
    timestamp: datetime
    dimensions: tuple[int, int]


# this will record details of a successful validation to logfire
m = Delivery(timestamp='2020-01-02T03:04:05Z', dimensions=['10', '20'])
print(repr(m.timestamp))
#> datetime.datetime(2020, 1, 2, 3, 4, 5, tzinfo=TzInfo(UTC))
print(m.dimensions)
#> (10, 20)

Delivery(timestamp='2020-01-02T03:04:05Z', dimensions=['10'])  # (2)!
  1. 设置 logfire 记录所有成功和失败的验证,使用 record='failure' 仅记录失败的验证,了解更多
  2. 由于 dimensions 过少,这将引发一个 ValidationError 异常,输入数据和验证错误的详细信息将被记录在 Logfire 中。

这将在 Logfire 平台中为您提供如下视图

Logfire Pydantic Integration

这只是一个玩具示例,但希望它能清楚地展示出为一个更复杂的应用程序配备监控工具的潜在价值。

了解更多关于 Pydantic Logfire

订阅我们的新闻通讯 The Pydantic Stack,获取关于 Pydantic、Logfire 和 Pydantic AI 的更新和教程。

为何使用 Pydantic?

  • 由类型提示驱动 — 使用 Pydantic,模式验证和序列化由类型注解控制;学习成本更低,代码量更少,并能与您的 IDE 和静态分析工具集成。了解更多…
  • 速度 — Pydantic 的核心验证逻辑是用 Rust 编写的。因此,Pydantic 是 Python 最快的数据验证库之一。了解更多…
  • JSON Schema — Pydantic 模型可以生成 JSON Schema,从而轻松与其他工具集成。了解更多…
  • 严格(Strict)宽松(Lax)模式 — Pydantic 可以在严格模式(数据不进行转换)或宽松模式(Pydantic 会在适当时尝试将数据强制转换为正确类型)下运行。了解更多…
  • DataclassesTypedDicts 等 — Pydantic 支持验证许多标准库类型,包括 dataclassTypedDict了解更多…
  • 自定义 — Pydantic 允许使用自定义验证器和序列化器,以多种强大的方式改变数据处理方式。了解更多…
  • 生态系统 — PyPI 上约有 8000 个包使用 Pydantic,包括像 FastAPIhuggingfaceDjango NinjaSQLModelLangChain 这样广受欢迎的库。了解更多…
  • 经过实战检验 — Pydantic 每月下载量超过 3.6 亿次,并被所有 FAANG 公司以及纳斯达克 25 家最大公司中的 20 家所使用。如果您想用 Pydantic 做某件事,很可能已经有人做过了。了解更多…

安装 Pydantic 非常简单:pip install pydantic

Pydantic 示例

为了看看 Pydantic 的实际效果,让我们从一个简单的示例开始,创建一个继承自 BaseModel 的自定义类

验证成功
from datetime import datetime

from pydantic import BaseModel, PositiveInt


class User(BaseModel):
    id: int  # (1)!
    name: str = 'John Doe'  # (2)!
    signup_ts: datetime | None  # (3)!
    tastes: dict[str, PositiveInt]  # (4)!


external_data = {
    'id': 123,
    'signup_ts': '2019-06-01 12:22',  # (5)!
    'tastes': {
        'wine': 9,
        b'cheese': 7,  # (6)!
        'cabbage': '1',  # (7)!
    },
}

user = User(**external_data)  # (8)!

print(user.id)  # (9)!
#> 123
print(user.model_dump())  # (10)!
"""
{
    'id': 123,
    'name': 'John Doe',
    'signup_ts': datetime.datetime(2019, 6, 1, 12, 22),
    'tastes': {'wine': 9, 'cheese': 7, 'cabbage': 1},
}
"""
  1. id 的类型是 int;仅使用注解的声明告诉 Pydantic 这个字段是必需的。字符串、字节或浮点数如果可能的话会被强制转换为整数;否则将引发异常。
  2. name 是一个字符串;因为它有默认值,所以不是必需的。
  3. signup_ts 是一个必需的 datetime 字段,但可以提供 None 值;Pydantic 会处理 Unix 时间戳整数(例如 1496498400)或表示日期和时间的字符串。
  4. tastes 是一个键为字符串、值为正整数的字典。PositiveInt 类型是 Annotated[int, annotated_types.Gt(0)] 的简写。
  5. 这里的输入是一个 ISO 8601 格式的日期时间,但 Pydantic 会将其转换为一个 datetime 对象。
  6. 这里的键是 bytes 类型,但 Pydantic 会负责将其强制转换为字符串。
  7. 类似地,Pydantic 会将字符串 '1' 强制转换为整数 1
  8. 我们通过将外部数据作为关键字参数传递给 User 来创建 User 的实例。
  9. 我们可以像访问模型的属性一样访问字段。
  10. 我们可以使用 model_dump() 将模型转换为字典。

如果验证失败,Pydantic 将引发一个错误,并详细说明出错的地方

验证错误
# continuing the above example...

from datetime import datetime
from pydantic import BaseModel, PositiveInt, ValidationError


class User(BaseModel):
    id: int
    name: str = 'John Doe'
    signup_ts: datetime | None
    tastes: dict[str, PositiveInt]


external_data = {'id': 'not an int', 'tastes': {}}  # (1)!

try:
    User(**external_data)  # (2)!
except ValidationError as e:
    print(e.errors())
    """
    [
        {
            'type': 'int_parsing',
            'loc': ('id',),
            'msg': 'Input should be a valid integer, unable to parse string as an integer',
            'input': 'not an int',
            'url': 'https://errors.pydantic.dev/2/v/int_parsing',
        },
        {
            'type': 'missing',
            'loc': ('signup_ts',),
            'msg': 'Field required',
            'input': {'id': 'not an int', 'tastes': {}},
            'url': 'https://errors.pydantic.dev/2/v/missing',
        },
    ]
    """
  1. 这里的输入数据是错误的 — id 不是一个有效的整数,并且 signup_ts 缺失。
  2. 尝试实例化 User 将会引发一个包含错误列表的 ValidationError

谁在使用 Pydantic?

成百上千的组织和软件包正在使用 Pydantic。一些全球知名的使用 Pydantic 的公司和组织包括

要查看更全面的使用 Pydantic 的开源项目列表,请参阅 GitHub 上的依赖项列表,或者您可以在 awesome-pydantic 中找到一些使用 Pydantic 的优秀项目。