pydantic学习

pyantic 学习

pydantic enforces type hints at runtime, and provides user friendly errors when data is invalid.

pydantic在运行时强制执行类型检测,并在数据无效时提供用户友好的错误。


from datetime import datetime
from typing import List
from pydantic import BaseModel

class User(BaseModel):
    id: int
    name = 'John Doe'
    signup_ts: 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)
print(repr(user.signup_ts))
print(user.friends)
print(user.dict())

常用typing

Loading Disqus comments...
Table of Contents