【问题标题】:Python and mypy: creating a generic collection with typebound based on a ProtocolPython 和 mypy:基于协议创建具有类型绑定的泛型集合
【发布时间】:2021-07-18 18:16:16
【问题描述】:

我想创建一个通用容器类,其中类型的边界基于实现协议,如下所示:

class Nameable(Protocol):
    def name(self) -> str:
        ...


T = TypeVar("T", bound=Nameable)


class NameableList(Generic[T]):
   ...


class Foo:
    _name: str
    def name(self) -> str:
        return self._name


x = NameableList[Foo]

在这样做时,mypy 坚持 Foo 必须是 Nameable 的子类型——这不是我想要的(Foo 只是实现了 Nameable 协议)

任何帮助将不胜感激。

【问题讨论】:

  • 我刚刚意识到边界强制执行子类型要求。这仍然使我最初的问题保持活力 - 我们如何对泛型类型强制执行协议约束?
  • 我在您的代码中没有看到任何 mypy 错误。

标签: python python-3.x mypy structural-typing


【解决方案1】:

据我所知和理解,这已经可以满足您的需求了。

例如当我尝试时

y = NameableList[int]

我收到以下 mypy 错误:

protocols.py:22: error: Type argument "builtins.int" of "NameableList" must be a subtype of "Nameable"
protocols.py:22: error: Value of type variable "T" of "NameableList" cannot be "int"
Found 2 errors in 1 file (checked 1 source file)

即泛型允许Foo,因为它遵守协议(不是因为它继承自Nameable),但不允许int,因为它没有。

我正在使用 Python 3.9.2 和 mypy==0.812。也许您使用的旧版本还不支持此功能?

【讨论】:

  • 是的,这行得通 - 我自己的代码中有一些其他问题导致了问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-09
  • 2023-03-14
  • 1970-01-01
  • 2014-12-09
  • 2016-07-02
  • 1970-01-01
  • 2022-01-21
相关资源
最近更新 更多