pydantic.mypy
This module includes classes and functions designed specifically for use with the mypy plugin.
Bases: Plugin
The Pydantic mypy plugin.
Default: PydanticPluginConfig(options)
def get_base_class_hook(fullname: str) -> Callable[[ClassDefContext], bool] | None
Update Pydantic model class.
Callable[[ClassDefContext], bool] | None
def get_metaclass_hook(fullname: str) -> Callable[[ClassDefContext], None] | None
Update Pydantic ModelMetaclass definition.
Callable[[ClassDefContext], None] | None
def get_function_hook(fullname: str) -> Callable[[FunctionContext], Type] | None
Adjust the return type of the Field function.
Callable[[FunctionContext], Type] | None
def get_method_hook(fullname: str) -> Callable[[MethodContext], Type] | None
Adjust return type of from_orm method call.
Callable[[MethodContext], Type] | None
def get_class_decorator_hook(fullname: str) -> Callable[[ClassDefContext], None] | None
Mark pydantic.dataclasses as dataclass.
Mypy version 1.1.1 added support for @dataclass_transform decorator.
Callable[[ClassDefContext], None] | None
def report_config_data(ctx: ReportConfigContext) -> dict[str, Any]
Return all plugin config data.
Used by mypy to determine if cache needs to be discarded.
dict[str, Any]
A Pydantic mypy plugin config holder.
Type: bool
Type: bool
Type: bool
Type: bool
def to_data() -> dict[str, Any]
Returns a dict of config names to their values.
dict[str, Any]
Based on mypy.plugins.dataclasses.DataclassAttribute.
Default: name
Default: alias
Default: has_dynamic_alias
Default: has_default
Default: line
Default: column
Default: type
Default: info
def to_argument(
current_info: TypeInfo,
typed: bool,
force_optional: bool,
use_alias: bool,
) -> Argument
Based on mypy.plugins.dataclasses.DataclassAttribute.to_argument.
Argument
def expand_type(current_info: TypeInfo) -> Type | None
Based on mypy.plugins.dataclasses.DataclassAttribute.expand_type.
Type | None
def to_var(current_info: TypeInfo, use_alias: bool) -> Var
Based on mypy.plugins.dataclasses.DataclassAttribute.to_var.
Var
def serialize() -> JsonDict
Based on mypy.plugins.dataclasses.DataclassAttribute.serialize.
JsonDict
@classmethod
def deserialize(
cls,
info: TypeInfo,
data: JsonDict,
api: SemanticAnalyzerPluginInterface,
) -> PydanticModelField
Based on mypy.plugins.dataclasses.DataclassAttribute.deserialize.
PydanticModelField
def expand_typevar_from_subtype(sub_type: TypeInfo) -> None
Expands type vars in the context of a subtype when an attribute is inherited from a generic super type.
None
Transform the BaseModel subclass according to the plugin settings.
Type: set[str] Default: \{'extra', 'frozen', 'from_attributes', 'populate_by_name', 'alias_generator'\}
Default: plugin_config
def transform() -> bool
Configures the BaseModel subclass according to the plugin settings.
In particular:
- determines the model config and fields,
- adds a fields-aware signature for the initializer and construct methods
- freezes the class if frozen = True
- stores the fields, config, and if the class is settings in the mypy metadata for access by subclasses
bool
def adjust_decorator_signatures() -> None
When we decorate a function f with pydantic.validator(...), pydantic.field_validator
or pydantic.serializer(...), mypy sees f as a regular method taking a self instance,
even though pydantic internally wraps f with classmethod if necessary.
Teach mypy this by marking any function whose outermost decorator is a validator(),
field_validator() or serializer() call as a classmethod.
None
def collect_config() -> ModelConfigData
Collects the values of the config attributes that are used by the plugin, accounting for parent classes.
ModelConfigData
def collect_fields(model_config: ModelConfigData) -> list[PydanticModelField] | None
Collects the fields for the model, accounting for parent classes.
list[PydanticModelField] | None
def collect_field_from_stmt(
stmt: AssignmentStmt,
model_config: ModelConfigData,
) -> PydanticModelField | None
Get pydantic model field from statement.
PydanticModelField | None — A pydantic model field if it could find the field in statement. Otherwise, None.
The statement.
Configuration settings for the model.
def add_initializer(
fields: list[PydanticModelField],
config: ModelConfigData,
is_settings: bool,
) -> None
Adds a fields-aware __init__ method to the class.
The added __init__ will be annotated with types vs. all Any depending on the plugin settings.
None
def add_model_construct_method(
fields: list[PydanticModelField],
config: ModelConfigData,
) -> None
Adds a fully typed model_construct classmethod to the class.
Similar to the fields-aware init method, but always uses the field names (not aliases), and does not treat settings fields as optional.
None
def set_frozen(fields: list[PydanticModelField], frozen: bool) -> None
Marks all fields as properties so that attempts to set them trigger mypy errors.
This is the same approach used by the attrs and dataclasses plugins.
None
def get_config_update(name: str, arg: Expression) -> ModelConfigData | None
Determines the config update due to a single kwarg in the ConfigDict definition.
Warns if a tracked config attribute is set to a value the plugin doesn’t know how to interpret (e.g., an int)
ModelConfigData | None
@staticmethod
def get_has_default(stmt: AssignmentStmt) -> bool
Returns a boolean indicating whether the field defined in stmt is a required field.
bool
@staticmethod
def get_alias_info(stmt: AssignmentStmt) -> tuple[str | None, bool]
Returns a pair (alias, has_dynamic_alias), extracted from the declaration of the field defined in stmt.
has_dynamic_alias is True if and only if an alias is provided, but not as a string literal.
If has_dynamic_alias is True, alias will be None.
tuple[str | None, bool]
def get_field_arguments(
fields: list[PydanticModelField],
typed: bool,
force_all_optional: bool,
use_alias: bool,
) -> list[Argument]
Helper function used during the construction of the __init__ and model_construct method signatures.
Returns a list of mypy Argument instances for use in the generated signatures.
list[Argument]
def should_init_forbid_extra(
fields: list[PydanticModelField],
config: ModelConfigData,
) -> bool
Indicates whether the generated __init__ should get a **kwargs at the end of its signature.
We disallow arbitrary kwargs if the extra config setting is “forbid”, or if the plugin config says to, unless a required dynamic alias is present (since then we can’t determine a valid signature).
bool
@staticmethod
def is_dynamic_alias_present(
fields: list[PydanticModelField],
has_alias_generator: bool,
) -> bool
Returns whether any fields on the model have a “dynamic alias”, i.e., an alias that cannot be determined during static analysis.
bool
Pydantic mypy plugin model config class.
Default: forbid_extra
Default: frozen
Default: from_attributes
Default: populate_by_name
Default: has_alias_generator
def get_values_dict() -> dict[str, Any]
Returns a dict of Pydantic model config names to their values.
It includes the config if config value is not None.
dict[str, Any]
def update(config: ModelConfigData | None) -> None
Update Pydantic model config values.
None
def setdefault(key: str, value: Any) -> None
Set default value for Pydantic model config if config value is None.
None
def parse_mypy_version(version: str) -> Tuple[int, ...]
Parse mypy string version to tuple of ints.
This function is included here rather than the mypy plugin file because the mypy plugin file cannot be imported outside a mypy run.
It parses normal version like 0.930 and dev version
like 0.940+dev.04cac4b5d911c4f9529e6ce86a27b44f28846f5d.dirty.
Tuple[int, ...] — A tuple of ints. e.g. (0, 930).
The mypy version string.
def plugin(version: str) -> type[Plugin]
version is the mypy version string.
We might want to use this to print a warning if the mypy version being used is newer, or especially older, than we expect (or need).
type[Plugin]
The mypy version string.
def from_attributes_callback(ctx: MethodContext) -> Type
Raise an error if from_attributes is not enabled.
Type
def error_from_attributes(
model_name: str,
api: CheckerPluginInterface,
context: Context,
) -> None
Emits an error when the model does not have from_attributes=True.
None
def error_invalid_config_value(
name: str,
api: SemanticAnalyzerPluginInterface,
context: Context,
) -> None
Emits an error when the config value is invalid.
None
def error_required_dynamic_aliases(
api: SemanticAnalyzerPluginInterface,
context: Context,
) -> None
Emits required dynamic aliases error.
This will be called when warn_required_dynamic_aliases=True.
None
def error_unexpected_behavior(
detail: str,
api: CheckerPluginInterface | SemanticAnalyzerPluginInterface,
context: Context,
) -> None
Emits unexpected behavior error.
None
def error_untyped_fields(api: SemanticAnalyzerPluginInterface, context: Context) -> None
Emits an error when there is an untyped field in the model.
None
def error_default_and_default_factory_specified(
api: CheckerPluginInterface,
context: Context,
) -> None
Emits an error when Field has both default and default_factory together.
None
def add_method(
api: SemanticAnalyzerPluginInterface | CheckerPluginInterface,
cls: ClassDef,
name: str,
args: list[Argument],
return_type: Type,
self_type: Type | None = None,
tvar_def: TypeVarDef | None = None,
is_classmethod: bool = False,
) -> None
Very closely related to mypy.plugins.common.add_method_to_class, with a few pydantic-specific changes.
None
def parse_toml(config_file: str) -> dict[str, Any] | None
Returns a dict of config keys to values.
It reads configs from toml file and returns None if the file is not a toml file.
dict[str, Any] | None
Default: 'pydantic-mypy'
Default: 'pydantic-mypy-metadata'
Default: 'pydantic.main.BaseModel'
Default: 'pydantic_settings.main.BaseSettings'
Default: 'pydantic._internal._model_construction.ModelMetaclass'
Default: 'pydantic.fields.Field'
Default: 'pydantic.dataclasses.dataclass'
Default: \{'pydantic.functional_validators.field_validator', 'pydantic.functional_validators.model_validator', 'pydantic.functional_serializers.serializer', 'pydantic.functional_serializers.model_serializer', 'pydantic.deprecated.class_validators.validator', 'pydantic.deprecated.class_validators.root_validator'\}
Default: parse_mypy_version(mypy_version)
Default: 'builtins' if MYPY_VERSION_TUPLE >= (0, 930) else '__builtins__'
Default: ErrorCode('pydantic-orm', 'Invalid from_attributes call', 'Pydantic')
Default: ErrorCode('pydantic-config', 'Invalid config value', 'Pydantic')
Default: ErrorCode('pydantic-alias', 'Dynamic alias disallowed', 'Pydantic')
Default: ErrorCode('pydantic-unexpected', 'Unexpected behavior', 'Pydantic')
Default: ErrorCode('pydantic-field', 'Untyped field disallowed', 'Pydantic')
Default: ErrorCode('pydantic-field', 'Invalid Field defaults', 'Pydantic')