Python 和 mypy:基于协议创建带有类型绑定的通用集合

Python and mypy: creating a generic collection with typebound based on a Protocol

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

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 协议)

如有任何帮助,我们将不胜感激。

据我所知,这已经满足了您的要求。

例如当我尝试

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。也许您使用的旧版本还不支持此功能?