Pydantic:数据类与 BaseModel

Pydantic: dataclass vs BaseModel

使用 Pydantic 的数据类与 BaseModel 相比有哪些优点和缺点? Pydantic 的数据类在另一个 python 模块中是否存在任何性能问题或更容易?

您的问题已在 Pydantic 的 documentation 中得到解答,具体而言:

Keep in mind that pydantic.dataclasses.dataclass is a drop-in replacement for dataclasses.dataclass with validation, not a replacement for pydantic.BaseModel (with a small difference in how initialization hooks work). There are cases where subclassing pydantic.BaseModel is the better choice.

For more information and discussion see samuelcolvin/pydantic#710.

讨论 link 将为您提供一些您正在寻找的上下文。一般来说,Pydantic 的 BaseModel 实现不一定与 Python 的 dataclass 实现相同。上一期中引用的例子就是一个很好的例子:

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

@dataclass
class A:
    x: List[int] = []

# Above definition with a default of `[]` will result in:
#   ValueError: mutable default <class 'list'> for field x is not allowed: use default_factory
# If you resolve this, the output will read as in the comments below.

class B(BaseModel):
    x: List[int] = []

print(A(x=[1, 2]), A(x=[3, 4])) # Output: A(x=[1, 2]) A(x=[3, 4])
print(B(x=[1, 2]), B(x=[3, 4])) # Output: x=[1, 2] x=[3, 4]

如果您首先想要的是 dataclass 行为,然后通过一些 Pydantic 验证功能简单地增强它,那么 pydantic.dataclasses.dataclass 方法可能就是您想要的。否则,BaseModel 可能就是您想要的。

BaseModel 的 init 函数与 dataclass 的 init 函数不同

@dataclass()
class Foo:
    number: int

class Bar(BaseModel):
    number: int

f = Foo(number = 1.4)
b = Bar(number = 1.4)
print(f)
print(b)

输出:

Foo(number=1.4)
number=1