Pydantic set attribute/field to model dynamically

Question:

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 ?

Asked By: jossefaz

||

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)
    """
Answered By: Kwibus

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')
Answered By: Kieran101
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.