pydantic's `Field`'s default value ignores constraint checks

Viewed 100
from pydantic import BaseModel

class User(BaseModel):
  age: int = Field('foo', ge=0)


User()  # doesn't raise an error
# User(age='foo')

Why doesn't this raise an error since a string foo is passed even though an int is expected?

User(age='foo') however raises the ValidationError as expected.

1 Answers

This connected to the config that you can add to all of your models. By default the default of Fields are excluding from validation, simply assuming that the programmer puts a proper default value. However, if you want to enforce validation you cann enforce it by adding a Config to your model:

class User(BaseModel):
  age: int = Field('foo', ge=0)

  class Config(BaseConfig):
      validate_all = True


if __name__ == "__main__":
    User()  # Now raise an error

Also have a look at the other options for configs in the the docs: https://pydantic-docs.helpmanual.io/usage/model_config/

Related