Python基于类型提示的数据解析和验证库pydantic

首页 / 文章分类 / 正文

简介

pydantic使用python类型注释进行数据验证和设置管理,在运行时强制类型提示,并在数据无效时提供用户友好的错误。

数百个组织和软件包正在使用pydantic,包括:

  1. FastAPI
  2. Jupyter
  3. Microsoft
  4. Amazon的GluonTS
  5. NSA的WALKOFF
  6. Uber的Ludwig
  7. ……

特点:

  • 与IDE/linter配合良好
  • 双用途
  • 快速
  • 验证复杂数据
  • 可扩展
  • 集成dataclass

安装

pip install pydantic 

初试

from typing import List from datetime import datetime from pydantic import BaseModel, ValidationError   class User(BaseModel):     id: int     name = 'John Doe'     signup_ts: datetime = None     friends: List[int] = []   # 正确调用 user = User(id=1, name='XerCis', signup_ts='2020-05-20 13:14', friends=[1, 2, 3]) print(user.id) print(user.signup_ts) print(user.friends)  # 错误调用 try:     User(signup_ts='not datetime', friends=[1, 2, 'not int']) except ValidationError as e:     print(e.json()) 

正确调用可以将对象信息输出
错误调用的具体原因很明确:没提供id、提供的signup_ts和friends类型出错

1 2020-05-20 13:14:00 [1, 2, 3] [   {     "loc": [       "id"     ],     "msg": "field required",     "type": "value_error.missing"   },   {     "loc": [       "signup_ts"     ],     "msg": "invalid datetime format",     "type": "value_error.datetime"   },   {     "loc": [       "friends",       2     ],     "msg": "value is not a valid integer",     "type": "type_error.integer"   } ] 

PyCharm插件

Python基于类型提示的数据解析和验证库pydantic
PyCharm的自动完成会进行类型提示

Python基于类型提示的数据解析和验证库pydantic

推荐阅读

  1. Python 类的 6 种替代方案

参考文献

  1. pydantic官方文档
  2. pydantic用法
  3. pydantic: Data parsing and validation using Python type hints