我以前从未使用过 pydantic,因此以下可能不是最佳解决方案,但根据文档,您可以使用__post_init__
dunder 方法dataclass
在将值转换为指定类型之前运行代码:
from typing import Optional
from pydantic.dataclasses import dataclass
from pydantic import validator
@dataclass
class Person:
name: Optional[str] = None
def __post_init__(self):
if not isinstance(self.name, str):
print(f'Careful! Your name, {self.name}, is not a string!')
@validator('name')
def name_must_be_str(cls, v):
if type(v) is not str:
raise TypeError("'name' must be str, not " + type(v).__name__)
return v
print(Person(1))
# Careful! Your name, 1, is not a string!
# Person(name='1')
还有一些预验证器可以指定为@validator('name', pre=True)
,它们还在转换前运行代码:
@dataclass
class Person:
name: Optional[str] = None
@validator('name', pre=True)
def name_must_be_str(cls, v):
if type(v) is not str:
raise TypeError("'name' must be str, not " + type(v).__name__)
return v
print(Person(1))
但对我来说,由于某种原因,它们返回了两个相同的错误:
ValidationError: 2 validation errors
name
'name' must be str, not int (type=type_error)
name
'name' must be str, not int (type=type_error)