其他分享
首页 > 其他分享> > pydantic学习与使用-6.dataclasses 验证器

pydantic学习与使用-6.dataclasses 验证器

作者:互联网

前言

validator 验证器也可以应用于 pydantic dataclasses.

pydantic dataclasses

pydantic 里面的 dataclassesdata 是 dataclasses.dataclass 和 validation 的结合。

from datetime import datetime

from pydantic import validator
from pydantic.dataclasses import dataclass


@dataclass
class DemoDataclass:
    ts: datetime = None

    @validator('ts', pre=True, always=True)
    def set_ts_now(cls, v):
        return v or datetime.now()


print(DemoDataclass())
# > DemoDataclass(ts=datetime.datetime(2021, 12, 31, 15, 4, 57, 631059))
print(DemoDataclass(ts='2017-11-08T14:00'))
# > DemoDataclass(ts=datetime.datetime(2017, 11, 8, 14, 0))

使用示例

validator 验证同样适用pre 和 each_item 验证器

from pydantic import validator
from pydantic.dataclasses import dataclass
from typing import List


@dataclass
class User(object):
    name: str
    age: int
    friends: List[int]

    @validator('name')
    def name_must_contain_space(cls, v):
        if ' ' not in v:
            raise ValueError('must contain a space')
        return v

    @validator('age')
    def check_age(cls, v):
        if v < 18:
            raise ValueError('age less then 18')
        return v

    @validator('friends', each_item=True)
    def check_friends(cls, v):
        assert v >= 2, f'{v} is not greater then 2'
        return v


user = User(name='yo yo',
            age=20,
            friends=[2, 3, 4])
print(user) # User(name='yo yo', age=20, friends=[2, 3, 4])
print(user.name)   # yo yo
print(user.age)    # 20
print(user.friends)   # [2, 3, 4]

标签:验证,age,dataclasses,ts,datetime,validator,pydantic
来源: https://www.cnblogs.com/yoyoketang/p/15918430.html