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 ?
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)
"""
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')
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 ?
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)
"""
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')