Skip to content

Add get_dynamic_class_hook to create_model in pydantic mypy plugin #12031

@albertferras-vrf

Description

@albertferras-vrf

Initial Checks

  • I have searched Google & GitHub for similar requests and couldn't find anything
  • I have read and followed the docs and still think this feature is missing

Description

Pydantic provides a way to create models dynamically (create_model).
The problem is that mypy always complain about these models:

a.py content:

from pydantic import create_model, BaseModel
from pydantic.fields import Field

GeneratedModel = create_model(
    "MyModel",
    some_field=(int, Field(default=0))
)


class MyModel(BaseModel):
    a: int
    model: GeneratedModel

$ mypy a.py

a.py:12: error: Variable "a.GeneratedModel" is not valid as a type  [valid-type]
a.py:12: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases
Found 1 error in 1 file (checked 1 source file)

Currently, you are forced to add # type: ignore[valid-type] on each line where this model is used, which is a problem because it adds a lot of noise but also disables the check for all variables in the same line as this type: ignore.

I've asked in mypy github project and developers suggested pydantic's mypy plugin could be updated to use get_dynamic_class_hook for pydantic's create_model use-case.

Affected Components

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions