惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

云风的 BLOG
云风的 BLOG
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 叶小钗
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
V2EX
酷 壳 – CoolShell
酷 壳 – CoolShell
月光博客
月光博客
人人都是产品经理
人人都是产品经理
宝玉的分享
宝玉的分享
博客园 - 司徒正美
WordPress大学
WordPress大学
Microsoft Azure Blog
Microsoft Azure Blog
罗磊的独立博客
Vercel News
Vercel News
T
The Blog of Author Tim Ferriss
T
Tailwind CSS Blog
A
About on SuperTechFans
Apple Machine Learning Research
Apple Machine Learning Research
L
LangChain Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
V
Visual Studio Blog
S
SegmentFault 最新的问题
Google DeepMind News
Google DeepMind News
博客园 - 聂微东

博客园 - 漫思

python使用.env构建开发和生产环境 python项目的构建 nodejs构建CICD时的思考  成为 AI 智能体工程师的 10 个步骤 es6的 yield python 中的 yield 笔记本的A壳 thinkpad 更换 reduce() in Python python的字段赋值和取值的操作 python的语法类似于lodash分组展开,合并分组操作 SelectMany C# lodash 数组的常用做法 lodash里面的常用方法 技术的边界 Reduce 和 Transduce 的含义 尤雨溪创办的 VoidZero 官宣加入 Cloudflare,前端 Vite 等保持开源 Ramda 函数库参考教程 ramda es 数组的方法 flatmap map object.entity的教程 Map与FlatMap:在数据处理中的区别与联系 flat、flatmap与map的用法区别1 flat、flatmap与map的用法区别 AI不是从天而降,它经历了七十年三起三落:读懂AI的第三课 Agent 17 种架构模式 分析 & 思考 只有踩过坑才懂:前端生成唯一 ID,别用 Date.now ()了!试试它crypto.randomUUID() FastAPI python并发 代码是 AI 写的,生产事故谁背锅? AI Agent 走出 Demo 幻觉的唯一解药:Harness Engineering
欢迎使用 Pydantic¶
漫思 · 2026-04-28 · via 博客园 - 漫思

欢迎使用 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 Tuple

from pydantic import BaseModel


class Delivery(BaseModel):
    timestamp: datetime
    dimensions: 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 datetime

from pydantic import BaseModel, PositiveInt


class 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 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': {}}  

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 的很棒的项目。