Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pydantic set attribute/field to model dynamically

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 ?

like image 402
jossefaz Avatar asked Feb 12 '26 22:02

jossefaz


1 Answers

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)
    """
like image 97
Kwibus Avatar answered Feb 14 '26 12:02

Kwibus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!