当前位置: 首页 > news >正文

欢迎使用 Pydantic

欢迎使用 Pydantic¶

欢迎使用 Pydantic¶

CI Coverage
pypi CondaForge downloads
license

.

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

Pydantic 教程

 

快速且可扩展,Pydantic 与你的代码检查器/集成开发环境/大脑配合良好。以纯的、规范的 Python 3.8+ 定义数据应该如何;使用 Pydantic 对其进行验证。

成功

“迁移到 Pydantic V2”

使用 Pydantic V1 吗? 在应用程序中查看迁移指南以获取有关升级到 Pydantic V2 的注意事项!!

Pydantic Example
from datetime import datetime
from typing import Tuplefrom pydantic import BaseModelclass Delivery(BaseModel):timestamp: datetimedimensions: Tuple[int, int]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)

问题

“为什么 Pydantic 是这样命名的?”

Pydantic 咨询

 

“Pydantic”这个名字是“Py”和“pedantic”的混合词。“Py”部分表示该库与 Python 相关,而“pedantic”指的是该库在数据验证和类型强制方面的细致方法。

综合这些元素,“Pydantic”描述了我们的 Python 库,它提供了注重细节、严格的数据验证。

我们意识到具有讽刺意味的是,Pydantic V1 在其验证中并不严格,所以如果我们很“吹毛求疵”的话,在 V2 版本之前,“Pydantic”是一个用词不当的名称😉。

为什么使用 Pydantic?¶

  • 由类型提示驱动——借助 Pydantic,模式验证和序列化由类型注释控制;学习的更少,编写的代码更少,并且与您的 IDE 和静态分析工具集成。了解更多……

  • 速度——Pydantic 的核心验证逻辑是用 Rust 编写的。因此,Pydantic 是 Python 中最快的数据验证库之一。了解更多……

  • JSON 模式——Pydantic 模型可以生成 JSON 模式,从而便于与其他工具进行集成。了解更多……

  • 严格模式和宽松模式——Pydantic 可以在 strict=True 模式(数据不进行转换)或 strict=False 模式下运行(在适当的情况下,Pydantic 尝试将数据强制转换为正确类型)。了解更多……

    Python 函数库

     

  • 数据类、类型字典等——Pydantic 支持对许多标准库类型的验证,包括 dataclass 和 TypedDict 。了解更多……

  • 自定义——Pydantic 允许自定义验证器和序列化器以多种强大方式改变数据的处理方式。了解更多……

  • 生态系统——PyPI 上约有 8000 个包使用 Pydantic,包括像 FastAPI、 huggingface、Django Ninja、SQLModel 和 LangChain 这样极受欢迎的库。了解更多……

  • 经过实战检验——Pydantic 每月被下载超过 7000 万次,被所有 FAANG 公司以及纳斯达克 25 家最大公司中的 20 家所使用。如果你正试图用 Pydantic 做某事,那么可能其他人已经做过了。了解更多……

安装 Pydantic 就像这样简单: pip install pydantic

Pydantic 使用例子¶

Validation Successful
from datetime import datetimefrom pydantic import BaseModel, PositiveIntclass User(BaseModel):id: int  name: str = 'John Doe'  signup_ts: datetime | None  tastes: dict[str, PositiveInt]  external_data = {'id': 123,'signup_ts': '2019-06-01 12:22',  'tastes': {'wine': 9,b'cheese': 7,  'cabbage': '1',  },
}user = User(**external_data)  print(user.id)  
#> 123
print(user.model_dump())  
"""
{
    'id': 123,
    'name': 'John Doe',
    'signup_ts': datetime.datetime(2019, 6, 1, 12, 22),
    'tastes': {'wine': 9, 'cheese': 7, 'cabbage': 1},
}
"""

如果验证失败,Pydantic 会引发一个错误并详细说明哪里出错了:

Pydantic 教程

 

Validation Error
# continuing the above example...from pydantic import ValidationErrorclass User(BaseModel):id: intname: str = 'John Doe'signup_ts: datetime | Nonetastes: dict[str, PositiveInt]external_data = {'id': 'not an int', 'tastes': {}}  try:User(**external_data)  
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://pydantic.com.cn/errors/validation_errors#int_parsing',
        },
        {
            'type': 'missing',
            'loc': ('signup_ts',),
            'msg': 'Field required',
            'input': {'id': 'not an int', 'tastes': {}},
            'url': 'https://pydantic.com.cn/errors/validation_errors#missing',
        },
    ]
    """

谁在使用 Pydantic?¶

数百个组织和包正在使用 Pydantic。全球一些使用 Pydantic 的著名公司和组织包括:

数据模型

 

对于使用 Pydantic 的更全面的开源项目列表,请参阅 github 上的依赖项列表,或者您可以在 awesome-pydantic 中找到一些使用 Pydantic 的很棒的项目。