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插件

在這裏插入圖片描述
PyCharm的自動完成會進行類型提示

在這裏插入圖片描述




參考文獻

  1. pydantic官方文檔
  2. pydantic用法
  3. pydantic: Data parsing and validation using Python type hints
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章