from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel

class User(BaseModel):
    id: int
    name = 'John Doe'
    signup_ts: Optional[datetime] = None
    friends: List[int] = []

external_data = {
    'id': '123',
    'signup_ts': '2019-06-01 12:22',
    'friends': [1, 2, '3'],
}
user = User(**external_data)
print(user.id)
#> 123
print(repr(user.signup_ts))
#> datetime.datetime(2019, 6, 1, 12, 22)
print(user.friends)
#> [1, 2, 3]
print(user.dict())
"""
{
    'id': 123,
    'signup_ts': datetime.datetime(2019, 6, 1, 12, 22),
    'friends': [1, 2, 3],
    'name': 'John Doe',
}
"""

如果失败

from pydantic import ValidationError
try:
    User(signup_ts='broken', friends=[1, 2, 'not number'])
except ValidationError as e:
    print(e.json())

[
  {
    "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"
  }
]

基本原理

基于type hint 中的__annotation__ 实现. 好处是不需要额外学习微语言.

模型

from pydantic import BaseModel

class User(BaseModel):
    id: int # 必选
    name = 'Jane Doe' # 可选 因为提供了默认值, 类型也由默认值推定.

user = User(id='123') # 这里自动进行验证, 能自动转换的就自动转换 譬如 '123' --> 123

# 可以使用dict 查看所有属性 --- 值对.
assert user.dict() == dict(user) == {'id': 123, 'name': 'Jane Doe'}

模型具有以下方法和属性: