【问题标题】:Pydantic: dataclass vs BaseModelPydantic:数据类与 BaseModel
【发布时间】:2020-09-12 15:24:47
【问题描述】:

使用 Pydantic 的 dataclass 与 BaseModel 的优缺点是什么?是否存在任何性能问题或者 Pydantic 的数据类在其他 python 模块中是否更容易?

【问题讨论】:

标签: python pydantic


【解决方案1】:

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

请记住,pydantic.dataclasses.dataclass 是带有验证功能的 dataclasses.dataclass 的直接替代品,不是替代 pydantic.BaseModel 的替代品(初始化挂钩的工作方式略有不同)。在某些情况下,子类化 pydantic.BaseModel 是更好的选择。

有关更多信息和讨论,请参阅samuelcolvin/pydantic#710

讨论链接将为您提供一些您正在寻找的上下文。一般来说,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 可能就是你想要的。

【讨论】:

    【解决方案2】:

    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
    

    【讨论】:

      猜你喜欢
      • 2022-10-07
      • 2022-11-06
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 2021-05-27
      • 2022-06-14
      • 2021-09-29
      • 2020-05-26
      相关资源
      最近更新 更多