How to properly type hint a model constructor, e.g. function that takes a model class and returns a model instance?
from pydantic import BaseModel
class Point(BaseModel):
x: int
y: int
First approach:
def make_model_instance(model: type[BaseModel], **kwargs) -> BaseModel:
return model(**kwargs)
point: Point = make_model_instance(model=Point, x=1, y=2)
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Here the linter flags the call to make_model_instance, but only if I type hint point with Point.
Second approach:
from typing import TypeVar
ModelType = TypeVar("ModelType", bound=BaseModel)
def make_model_instance(model: ModelType, **kwargs) -> ModelType:
return model(**kwargs)
^~~~~~~~~~~~~~
point: Point = make_model_instance(model=Point, x=1, y=2)
^~~~~
Third approach:
from typing import TypeVar
ModelType = TypeVar("ModelType", bound=BaseModel)
def make_model_instance(model: type[ModelType], **kwargs) -> ModelType:
return model(**kwargs)
point: Point = make_model_instance(model=Point, x=1, y=2)
This appears to do the trick, no complaints from the linter, but I don't really know why.