1

I have defined and used a factory function roughly with the following code:

import typing as t
from pydantic import BaseModel

M = t.TypeVar("M", bound=t.Union[t.Dict, BaseModel])

def foo(factory: t.Type[M]) -> M:
    ...
    return factory(**{"key": "value"})


class MyModel(BaseModel):
    key: str

foo(MyModel)

I receive the error Incompatible return value type (got "Union[Dict[Any, Any], BaseModel]", expected "M") from the following code

What is the correct way to make this code acceptable by mypy?

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
hangc
  • 4,730
  • 10
  • 33
  • 66

1 Answers1

2

Specify the variants separately:

M = t.TypeVar("M", t.Dict, BaseModel)
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119