Allow defining type for dynamically generated types.
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 20.6k
- Fork
- 3.3k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
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
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia riproducendo l’esempio in a.py con mypy e verificando la diagnostica valid-type attuale. La modifica è completata quando un tipo prodotto da pydantic's create_model può essere usato nelle annotazioni senza ripetere valid-type ignores, mentre i controlli non correlati sulla stessa riga rimangono attivi.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- compilers
- Tipo di issue
- Funzionalità
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 30/100