Python · correctness
invalid-pydantic-field-default
python:invalid-pydantic-field-default Require literal Pydantic `Field` defaults to satisfy their declared contract.
- Code
- SARJ400
- Default
- error
- Fix
- none
- Languages
- python
Why
An invalid default lets a model begin with a value that contradicts its annotation or field bounds, moving a deterministic configuration error into runtime validation.
Fix
Choose a default allowed by the annotation and every literal `Field` bound, or widen the contract when the value is intentional.
Before / after
Executed by this rule’s unit tests.
Before
Default is outside the declared field bounds
from pydantic import BaseModel, Field
class RetryPolicy(BaseModel):
attempts: int = Field(default=0, gt=0)
After
Default satisfies the declared field bounds
from pydantic import BaseModel, Field
class RetryPolicy(BaseModel):
attempts: int = Field(default=1, gt=0)
Limits
- The rule checks direct public fields on classes that directly inherit Pydantic `BaseModel`.
- It reports only statically provable literal conflicts with nullability, `Literal` domains, and numeric or string-length bounds.
- Test and generated files are excluded.