簡介
pydantic使用python類型註釋進行數據驗證和設置管理,在運行時強制類型提示,並在數據無效時提供用戶友好的錯誤。
數百個組織和軟件包正在使用pydantic,包括:
特點:
- 與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的自動完成會進行類型提示