【问题标题】:mypy factory method with bound TypeVar绑定 TypeVar 的 mypy 工厂方法
【发布时间】:2020-11-24 10:56:54
【问题描述】:

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

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 接受此代码的正确方法是什么?

【问题讨论】:

    标签: python mypy


    【解决方案1】:

    分别指定变体:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-05
      • 1970-01-01
      • 2018-09-29
      • 1970-01-01
      相关资源
      最近更新 更多