A flake8 plugin to check Pydantic related code.
flake8_pydantic parses the AST to emit linting errors. As such,
it cannot accurately determine if a class is defined as a Pydantic model. However, it tries its best, using the following heuristics:
- The class inherits from
BaseModelorRootModel. - The class has a
model_configattribute set. - The class has a field defined with the
Fieldfunction. - The class has a field making use of
Annotated. - The class makes use of Pydantic decorators, such as
computed_fieldormodel_validator. - The class overrides any of the Pydantic methods, such as
model_dump.
Raise an error if the default argument of the Field function is positional.
class Model(BaseModel):
foo: int = Field(1)Although allowed at runtime by Pydantic, it does not comply with the typing specification (PEP 681) and type checkers will not be able to synthesize a correct __init__ method.
Instead, consider using an explicit keyword argument:
class Model(BaseModel):
foo: int = Field(default=1)Raise an error if a non-annotated attribute is defined inside a Pydantic model class.
class Model(BaseModel):
foo = 1 # Will error at runtimeRaise an error if the Field function
is used only to specify a default value.
class Model(BaseModel):
foo: int = Field(default=1)Instead, consider specifying the default value directly:
class Model(BaseModel):
foo: int = 1Raise an error if the default argument of the Field function is used together with Annotated.
class Model(BaseModel):
foo: Annotated[int, Field(default=1, description="desc")]To make type checkers aware of the default value, consider specifying the default value directly:
class Model(BaseModel):
foo: Annotated[int, Field(description="desc")] = 1Raise an error if the field name clashes with the annotation.
from datetime import date
class Model(BaseModel):
date: date | None = NoneBecause of how Python evaluates annotated assignments, unexpected issues can happen when using an annotation name that clashes with a field name. Pydantic will try its best to warn you about such issues, but can fail in complex scenarios (and the issue may even be silently ignored).
Instead, consider, using an alias or referencing your type under a different name:
from datetime import date
date_ = date
class Model(BaseModel):
date_aliased: date | None = Field(default=None, alias="date")
# or
date: date_ | None = NoneRaise an error if a Pydantic configuration is set with __pydantic_config__.
class Model(TypedDict):
__pydantic_config__ = {} # Type checkers will emit an errorAlthough allowed at runtime by Python, type checkers will emit an error as it is not allowed to assign values when defining a TypedDict.
Instead, consider using the with_config decorator:
@with_config({"str_to_lower": True})
class Model(TypedDict):
passAnd many more to come.
Once the rules of the plugin gets stable, the goal will be to implement them in Ruff, with autofixes when possible.