简体   繁体   English

Pydantic:数据类与 BaseModel

[英]Pydantic: dataclass vs BaseModel

What are the advantages and disadvantages of using Pydantic's dataclass vs BaseModel?使用 Pydantic 的数据类与 BaseModel 的优缺点是什么? Are there any performance issues or is it easier to Pydantic's dataclass in the other python module?在其他 python 模块中是否存在任何性能问题或 Pydantic 的数据类更容易?

Your question is answered in Pydantic's documentation , specifically: Pydantic 的文档中回答了您的问题,特别是:

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).请记住, pydantic.dataclasses.dataclass是带有验证的dataclasses.dataclass的直接替代品,而不是pydantic.BaseModel的替代品(初始化挂钩的工作方式略有不同)。 There are cases where subclassing pydantic.BaseModel is the better choice.在某些情况下,子类pydantic.BaseModel是更好的选择。

For more information and discussion see samuelcolvin/pydantic#710 .有关更多信息和讨论,请参阅samuelcolvin/pydantic#710

The discussion link will give you some of the context you are looking for.讨论链接将为您提供一些您正在寻找的上下文。 In general, Pydantic's BaseModel implementation is not bound to behave the same as Python's dataclass implementation.通常,Pydantic 的BaseModel实现不一定与 Python 的dataclass实现相同。 The example cited in the issue above is one good example:上述问题中引用的示例就是一个很好的示例:

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]

If what you want first and foremost is dataclass behavior and then to simply augment it with some Pydantic validation features, the pydantic.dataclasses.dataclass approach may be what you want.如果您首先想要的是dataclass行为,然后简单地使用一些 Pydantic 验证功能来增强它,那么pydantic.dataclasses.dataclass方法可能就是您想要的。 Otherwise, BaseModel is probably what you want.否则, BaseModel可能就是您想要的。

The init Function for BaseModel works differnt than the init for dataclass BaseModel 的 init Function 的工作方式与数据类的 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)

Output: Output:

Foo(number=1.4)
number=1

Another option is to use openapi-json-schema-generator with model generation only.另一种选择是仅使用model 代的 openapi-json-schema-generator It allows robust validation of many python data types against openapi/json schemas.它允许根据 openapi/json 模式对许多 python 数据类型进行可靠验证。 It

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM