pydantic set属性/字段动态模型

发布于 2025-01-25 13:16:51 字数 1095 浏览 1 评论 0 原文

根据 docs

允许_ moution

是否允许 setAttr (默认:true)

是否允许 setAttr

我有一个类:

class MyModel(BaseModel):

    field1:int

    class Config:
        allow_mutation = True

如果我尝试动态添加一个字段:

model1 = MyModel(field1=1)
model1.field2 = 2

并且我得到此错误:

  File "pydantic/main.py", line 347, in pydantic.main.BaseModel.__setattr__
ValueError: "MyModel" object has no field "field2"

显然,使用 setAttr 方法将导致相同的错误。

setattr(model1, 'field2', 2)

输出:

  File "pydantic/main.py", line 347, in pydantic.main.BaseModel.__setattr__
ValueError: "MyModel" object has no field "field2"

我在这里想念什么?

According to the docs:

allow_mutation

whether or not models are faux-immutable, i.e. whether setattr is allowed (default: True)

Well I have a class :

class MyModel(BaseModel):

    field1:int

    class Config:
        allow_mutation = True

If I try to add a field dynamically :

model1 = MyModel(field1=1)
model1.field2 = 2

And I get this error :

  File "pydantic/main.py", line 347, in pydantic.main.BaseModel.__setattr__
ValueError: "MyModel" object has no field "field2"

Obviously, using setattr method will lead to the same error.

setattr(model1, 'field2', 2)

Output:

  File "pydantic/main.py", line 347, in pydantic.main.BaseModel.__setattr__
ValueError: "MyModel" object has no field "field2"

What did I miss here ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

九命猫 2025-02-01 13:16:51

您可以在类中使用config对象,并将 extra 属性设置为“允许”,或将其用作 extra = extair = extair.allow kwargs在

从<<<<<<<< a href =“ https://pydantic-docs.helpmanual.io/usage/model_config/” rel =“ noreferrer”> docs :

from pydantic import BaseModel, ValidationError, Extra


class Model(BaseModel, extra=Extra.forbid):
    a: str


try:
    Model(a='spam', b='oh no')
except ValidationError as e:
    print(e)
    """
    1 validation error for Model
    b
      extra fields not permitted (type=value_error.extra)
    """

You can use the Config object within the class and set the extra attribute to "allow" or use it as extra=Extra.allow kwargs when declaring the model

Example from the docs :

from pydantic import BaseModel, ValidationError, Extra


class Model(BaseModel, extra=Extra.forbid):
    a: str


try:
    Model(a='spam', b='oh no')
except ValidationError as e:
    print(e)
    """
    1 validation error for Model
    b
      extra fields not permitted (type=value_error.extra)
    """
回忆追雨的时光 2025-02-01 13:16:51

使用 extair.Allow 放置一个示例,以回答问题。

from pydantic import BaseModel, ValidationError, Extra


class Model(BaseModel, extra=Extra.allow):
    a: str

my_model = Model(a="1")
my_model.b = "2"
# Model(a='1', b='2')

Putting an example using extra.allow that answers the question asked.

from pydantic import BaseModel, ValidationError, Extra


class Model(BaseModel, extra=Extra.allow):
    a: str

my_model = Model(a="1")
my_model.b = "2"
# Model(a='1', b='2')
段念尘 2025-02-01 13:16:51

为了记录,Pydantic V2已用“冷冻” 表明田地是人造的:

是否允许 setAttr 模型,即是否允许 setattr ,并且还为模型生成了 hash ()方法。如果所有属性都是可用的,则可能会使模型的实例可能存在。默认为false。

在v1上,此设置的倒数被称为 laster_muart , true 默认情况下。

但是 faux-immutability )不应与额外的属性处理 extra ),这是一个显示区别的小例子:

import pydantic

class ImmutableExample(pydantic.BaseModel, frozen=True):
    x: int

immutable_instance = ImmutableExample(x=3)
immutable_instance.x = 4  # ERROR: faux-immutability: cannot update field values!
immutable_instance.y = 123  # ERROR: `y` attr is unknown, no extra fields allowed!

class ExtraFieldAllowed(pydantic.BaseModel, extra="allow"):
    x: int

extra_field_instance = ExtraFieldAllowed(x=3)
extra_field_instance.x = 4  # OK
# ExtraFieldAllowed(x=4)
extra_field_instance.y = 3  # OK
# ExtraFieldAllowed(x=4, y=3)

For the record, Pydantic V2 has replaced allow_mutation with "frozen" to indicate fields are faux-immutable:

Whether models are faux-immutable, i.e. whether setattr is allowed, and also generates a hash() method for the model. This makes instances of the model potentially hashable if all the attributes are hashable. Defaults to False.

On V1, the inverse of this setting was called allow_mutation, and was True by default.

But faux-immutability (frozen) should not be confused with extra attribute handling (extra), here's a small example to show the difference:

import pydantic

class ImmutableExample(pydantic.BaseModel, frozen=True):
    x: int

immutable_instance = ImmutableExample(x=3)
immutable_instance.x = 4  # ERROR: faux-immutability: cannot update field values!
immutable_instance.y = 123  # ERROR: `y` attr is unknown, no extra fields allowed!

class ExtraFieldAllowed(pydantic.BaseModel, extra="allow"):
    x: int

extra_field_instance = ExtraFieldAllowed(x=3)
extra_field_instance.x = 4  # OK
# ExtraFieldAllowed(x=4)
extra_field_instance.y = 3  # OK
# ExtraFieldAllowed(x=4, y=3)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文