Skip to content

Allow defining type for dynamically generated types. #19360

Open
@albertferras-vrf

Description

@albertferras-vrf

Feature
Add a way to allow defining or overriding types for dynamically generated types, such as pydantic's create_model.

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

sample code (a.py)

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 tried things like these, with no luck:

# attempt 1
GeneratedModel: type[Any] = create_model(...)

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

GeneratedModel = cast(type[Any], GeneratedModel)

# attempt 3
def is_pydantic_model(model: Any) -> TypeGuard[BaseModel]:
    return isinstance(model, BaseModel)

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

But I always get the same [valid-type] warning everywhere where this type is used.

The actual real workaround today is to define the type in a different file and import from somewhere else, but that is already marked as bug .

edit: Fixed FieldInfo->Field

Metadata

Metadata

Assignees

No one assigned

    Labels

    featuretopic-pluginsThe plugin API and ideas for new plugins

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions