Skip to content

invalid-pydantic-field-default

Require literal Pydantic model-field defaults to satisfy their resolved contract.

Why

Pydantic does not validate defaults unless default validation is enabled. An invalid literal can therefore enter a model while contradicting its annotation or field bounds.

Fix

Choose a default allowed by the annotation and every literal Field bound, or widen the contract when the value is intentional.

Examples

Before — flagged Default is outside the declared field bounds
app/models.py
from typing import Annotated
from pydantic import BaseModel, Field
PositiveInt = Annotated[int, Field(gt=0)]
class RetryPolicy(BaseModel):
attempts: PositiveInt = 0
After — preferred Default satisfies the declared field bounds
app/models.py
from typing import Annotated
from pydantic import BaseModel, Field
PositiveInt = Annotated[int, Field(gt=0)]
class RetryPolicy(BaseModel):
attempts: PositiveInt = 1
Before — flagged A non-null field cannot default to None
app/models.py
from pydantic import BaseModel
class User(BaseModel):
display_name: str = None
After — preferred Declare None when it is an allowed default
app/models.py
from pydantic import BaseModel
class User(BaseModel):
display_name: str | None = None