我定义并使用了一个工厂函数,大致有以下代码:
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)