I am using Pydantic to validate my class data. In some cases after the class has been instantiated, I want to overwrite the value of a field, but I want to verify that the new value has the same type as defined in the Model
. I expect I should be able to use validators but I haven't seen an option for protecting the field after the object is created.
Is there a simple mechanism within pydantic which allows this type of validation?
from pydantic import BaseModel, validator
class MyModel(BaseModel):
some_field : str = None
@validator("some_field")
def verify_string(cls, v):
print(f"Verifying some_field value: {v}")
if not isinstance(v, str):
raise ValueError(f"some_field must be str; got type {type(v)}")
return v
# Instantiate model
m = MyModel(some_field = "test")
## prints: Verifying some_field value: test
print(m.some_field)
## prints: test
# Overwrite a field within invalid type
m.some_field = 100 # <-- this should raise value error
print(m.some_field)
## prints: 100
Sorry I found the solution -- use Config
and some validator
parameters.
class MyModel(BaseModel):
some_field : str = None
class Config:
validate_assignment = True
@validator(
"some_field", always=True, pre=True,
)
def verify_string(cls, v):
print(f"Verifying some_field value: {v}")
if not isinstance(v, str):
raise ValueError(f"some_field must be str; got type {type(v)}")
return v
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.