带有绑定 TypeVar 的 mypy 工厂方法

mypy factory method with bound TypeVar

我已经用下面的代码大致定义并使用了一个工厂函数:

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)

我收到来自以下代码的错误 Incompatible return value type (got "Union[Dict[Any, Any], BaseModel]", expected "M")

使这段代码被 mypy 接受的正确方法是什么?

分别指定变体:

M = t.TypeVar("M", t.Dict, BaseModel)