Skip to content
You're viewing docs for v2.0. See the latest version →

pydantic.mypy

This module includes classes and functions designed specifically for use with the mypy plugin.

PydanticPlugin

Bases: Plugin

The Pydantic mypy plugin.

Attributes

plugin_config

Default: PydanticPluginConfig(options)

Methods

get_base_class_hook

def get_base_class_hook(fullname: str) -> Callable[[ClassDefContext], bool] | None

Update Pydantic model class.

Returns

Callable[[ClassDefContext], bool] | None

get_metaclass_hook

def get_metaclass_hook(fullname: str) -> Callable[[ClassDefContext], None] | None

Update Pydantic ModelMetaclass definition.

Returns

Callable[[ClassDefContext], None] | None

get_function_hook

def get_function_hook(fullname: str) -> Callable[[FunctionContext], Type] | None

Adjust the return type of the Field function.

Returns

Callable[[FunctionContext], Type] | None

get_method_hook

def get_method_hook(fullname: str) -> Callable[[MethodContext], Type] | None

Adjust return type of from_orm method call.

Returns

Callable[[MethodContext], Type] | None

get_class_decorator_hook

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.

Returns

Callable[[ClassDefContext], None] | None

report_config_data

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.

Returns

dict[str, Any]


PydanticPluginConfig

A Pydantic mypy plugin config holder.

Attributes

init_forbid_extra

Type: bool

init_typed

Type: bool

warn_required_dynamic_aliases

Type: bool

debug_dataclass_transform

Type: bool

Methods

to_data

def to_data() -> dict[str, Any]

Returns a dict of config names to their values.

Returns

dict[str, Any]


PydanticModelField

Based on mypy.plugins.dataclasses.DataclassAttribute.

Attributes

name

Default: name

alias

Default: alias

has_dynamic_alias

Default: has_dynamic_alias

has_default

Default: has_default

line

Default: line

column

Default: column

type

Default: type

info

Default: info

Methods

to_argument

def to_argument(
    current_info: TypeInfo,
    typed: bool,
    force_optional: bool,
    use_alias: bool,
) -> Argument

Based on mypy.plugins.dataclasses.DataclassAttribute.to_argument.

Returns

Argument

expand_type

def expand_type(current_info: TypeInfo) -> Type | None

Based on mypy.plugins.dataclasses.DataclassAttribute.expand_type.

Returns

Type | None

to_var

def to_var(current_info: TypeInfo, use_alias: bool) -> Var

Based on mypy.plugins.dataclasses.DataclassAttribute.to_var.

Returns

Var

serialize

def serialize() -> JsonDict

Based on mypy.plugins.dataclasses.DataclassAttribute.serialize.

Returns

JsonDict

deserialize

@classmethod

def deserialize(
    cls,
    info: TypeInfo,
    data: JsonDict,
    api: SemanticAnalyzerPluginInterface,
) -> PydanticModelField

Based on mypy.plugins.dataclasses.DataclassAttribute.deserialize.

Returns

PydanticModelField

expand_typevar_from_subtype

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.

Returns

None


PydanticModelTransformer

Transform the BaseModel subclass according to the plugin settings.

Attributes

tracked_config_fields

Type: set[str] Default: \{'extra', 'frozen', 'from_attributes', 'populate_by_name', 'alias_generator'\}

plugin_config

Default: plugin_config

Methods

transform

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
Returns

bool

adjust_decorator_signatures

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.

Returns

None

collect_config

def collect_config() -> ModelConfigData

Collects the values of the config attributes that are used by the plugin, accounting for parent classes.

Returns

ModelConfigData

collect_fields

def collect_fields(model_config: ModelConfigData) -> list[PydanticModelField] | None

Collects the fields for the model, accounting for parent classes.

Returns

list[PydanticModelField] | None

collect_field_from_stmt

def collect_field_from_stmt(
    stmt: AssignmentStmt,
    model_config: ModelConfigData,
) -> PydanticModelField | None

Get pydantic model field from statement.

Returns

PydanticModelField | None — A pydantic model field if it could find the field in statement. Otherwise, None.

Parameters

stmt : AssignmentStmt

The statement.

model_config : ModelConfigData

Configuration settings for the model.

add_initializer

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.

Returns

None

add_model_construct_method

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.

Returns

None

set_frozen

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.

Returns

None

get_config_update

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)

Returns

ModelConfigData | None

get_has_default

@staticmethod

def get_has_default(stmt: AssignmentStmt) -> bool

Returns a boolean indicating whether the field defined in stmt is a required field.

Returns

bool

get_alias_info

@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.

Returns

tuple[str | None, bool]

get_field_arguments

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.

Returns

list[Argument]

should_init_forbid_extra

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).

Returns

bool

is_dynamic_alias_present

@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.

Returns

bool


ModelConfigData

Pydantic mypy plugin model config class.

Attributes

forbid_extra

Default: forbid_extra

frozen

Default: frozen

from_attributes

Default: from_attributes

populate_by_name

Default: populate_by_name

has_alias_generator

Default: has_alias_generator

Methods

get_values_dict

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.

Returns

dict[str, Any]

update

def update(config: ModelConfigData | None) -> None

Update Pydantic model config values.

Returns

None

setdefault

def setdefault(key: str, value: Any) -> None

Set default value for Pydantic model config if config value is None.

Returns

None


parse_mypy_version

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.

Returns

Tuple[int, ...] — A tuple of ints. e.g. (0, 930).

Parameters

version : str

The mypy version string.


plugin

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).

Returns

type[Plugin]

Parameters

version : str

The mypy version string.


from_attributes_callback

def from_attributes_callback(ctx: MethodContext) -> Type

Raise an error if from_attributes is not enabled.

Returns

Type


error_from_attributes

def error_from_attributes(
    model_name: str,
    api: CheckerPluginInterface,
    context: Context,
) -> None

Emits an error when the model does not have from_attributes=True.

Returns

None


error_invalid_config_value

def error_invalid_config_value(
    name: str,
    api: SemanticAnalyzerPluginInterface,
    context: Context,
) -> None

Emits an error when the config value is invalid.

Returns

None


error_required_dynamic_aliases

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.

Returns

None


error_unexpected_behavior

def error_unexpected_behavior(
    detail: str,
    api: CheckerPluginInterface | SemanticAnalyzerPluginInterface,
    context: Context,
) -> None

Emits unexpected behavior error.

Returns

None


error_untyped_fields

def error_untyped_fields(api: SemanticAnalyzerPluginInterface, context: Context) -> None

Emits an error when there is an untyped field in the model.

Returns

None


error_default_and_default_factory_specified

def error_default_and_default_factory_specified(
    api: CheckerPluginInterface,
    context: Context,
) -> None

Emits an error when Field has both default and default_factory together.

Returns

None


add_method

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.

Returns

None


parse_toml

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.

Returns

dict[str, Any] | None


CONFIGFILE_KEY

Default: 'pydantic-mypy'

METADATA_KEY

Default: 'pydantic-mypy-metadata'

BASEMODEL_FULLNAME

Default: 'pydantic.main.BaseModel'

BASESETTINGS_FULLNAME

Default: 'pydantic_settings.main.BaseSettings'

MODEL_METACLASS_FULLNAME

Default: 'pydantic._internal._model_construction.ModelMetaclass'

FIELD_FULLNAME

Default: 'pydantic.fields.Field'

DATACLASS_FULLNAME

Default: 'pydantic.dataclasses.dataclass'

DECORATOR_FULLNAMES

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'\}

MYPY_VERSION_TUPLE

Default: parse_mypy_version(mypy_version)

BUILTINS_NAME

Default: 'builtins' if MYPY_VERSION_TUPLE >= (0, 930) else '__builtins__'

ERROR_ORM

Default: ErrorCode('pydantic-orm', 'Invalid from_attributes call', 'Pydantic')

ERROR_CONFIG

Default: ErrorCode('pydantic-config', 'Invalid config value', 'Pydantic')

ERROR_ALIAS

Default: ErrorCode('pydantic-alias', 'Dynamic alias disallowed', 'Pydantic')

ERROR_UNEXPECTED

Default: ErrorCode('pydantic-unexpected', 'Unexpected behavior', 'Pydantic')

ERROR_UNTYPED

Default: ErrorCode('pydantic-field', 'Untyped field disallowed', 'Pydantic')

ERROR_FIELD_DEFAULTS

Default: ErrorCode('pydantic-field', 'Invalid Field defaults', 'Pydantic')