Allow defining type for dynamically generated types.
Nobody has claimed this yet.
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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