python / python/mypy

Allow defining type for dynamically generated types.

Open
#19,360 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

feature topic-plugins
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the sample in a.py with mypy and reviewing the current valid-type diagnostic. The change is done when a type produced by pydantic's create_model can be used in annotations without repeated valid-type ignores, while unrelated checks on the same line remain active.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.