I have recently found the power of Pydantic validators and proceeded to uses them in one of my personal projects.
However, I've encountered a problem: the failure of one validator does not stop the execution of the following validators, resulting in an Exception.
class Field(BaseModel):
name: constr(min_length=1, max_length=32)
type: constr(min_length=1, max_length=32)
length: Optional[int]
nullable: bool
class Unique(BaseModel):
name: constr(min_length=1, max_length=32)
unique_fields: List[constr(min_length=1, max_length=32)]
class Resource(BaseModel):
name: constr(min_length=1, max_length=32)
table_name: constr(min_length=1, max_length=32)
fields: List[Field]
primary_key: constr(min_length=1, max_length=32)
uniques: Optional[List[Unique]]
@validator('name')
def resource_name_must_be_pure_string(cls, v):
if not v.isalpha():
raise ValueError(ONLY_ALPHA_ERR.format("Resource name"))
return v
@validator('table_name')
def table_name_must_be_pure_string(cls, v):
if not v.isalpha():
raise ValueError(ONLY_ALPHA_ERR.format("Table name"))
return v
@validator('fields', pre=True)
def field_name_must_be_pure_string(cls, v):
fieldnames = [field["name"] for field in v]
print(fieldnames)
for fieldname in fieldnames:
if not fieldname.replace('_', '').isalpha():
print('was here')
raise ValueError("A field's name can only contain alphabetic characters and '_'.")
return v
@validator('primary_key')
def primary_key_must_be_in_fields(cls, v, values):
fieldnames = [field.name for field in values["fields"]]
if v not in fieldnames:
raise ValueError(f"Primary key `{v}` should be one of the input fields.")
return v
The method field_name_must_be_pure_string prints "was here", therefore the ValueError exception should have been raised, but the execution proceeds to the next validator, which would be primary_key_must_be_in_fields, that fails because the preceding list of fields was invalid.
What would be the solution to this corner case?
Late answer, but managed to avoid getting a crash by using the following:
@validator('primary_key')
def primary_key_must_be_in_fields(cls, v, values):
if "fields" not in values:
return
fieldnames = [field.name for field in values["fields"]]
if v not in fieldnames:
raise ValueError(f"Primary key `{v}` should be one of the input fields.")
return v
It took a while to realise that Pydantic will do all validations and will not stop at first exception.