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.

ModelConfigData

Pydantic mypy plugin model config class.

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]

setdefault

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

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

Returns

None

update

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

Update Pydantic model config values.

Returns

None

PydanticModelField

Based on mypy.plugins.dataclasses.DataclassAttribute.

Methods

deserialize

@classmethod

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

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

Returns

PydanticModelField

expand_type

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

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

Returns

Type | None

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

serialize

def serialize() -> JsonDict

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

Returns

JsonDict

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

to_var

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

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

Returns

Var

PydanticModelTransformer

Transform the BaseModel subclass according to the plugin settings.

Attributes

tracked_config_fields

A set of field configs that the plugin has to track their value.

Type: set[str]

Methods

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

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

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

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_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_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]

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

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

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

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

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

PydanticPlugin

Bases: Plugin

The Pydantic mypy plugin.

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_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

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_metaclass_hook

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

Update Pydantic ModelMetaclass definition.

Returns

Callable[[ClassDefContext], None] | 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

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

Whether to add a **kwargs at the end of the generated __init__ signature.

Type: bool

init_typed

Whether to annotate fields in the generated __init__.

Type: bool

warn_required_dynamic_aliases

Whether to raise required dynamic aliases error.

Type: bool

debug_dataclass_transform

Whether to not reset dataclass_transform_spec attribute of ModelMetaclass for testing purposes.

Type: bool

Methods

to_data

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

Returns a dict of config names to their values.

Returns

dict[str, Any]

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

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

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

from_attributes_callback

def from_attributes_callback(ctx: MethodContext) -> Type

Raise an error if from_attributes is not enabled.

Returns

Type

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

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.