简体   繁体   English

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

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

I'd like to create a generic container class, where the bounds on the type are based on implementing a protocol, like this:我想创建一个通用容器 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]

In doing this, mypy insists that Foo must be a subtype of Nameable -- which is not what I want (Foo just implements the Nameable protocol)在这样做时,mypy 坚持 Foo 必须是 Nameable 的子类型——这不是我想要的(Foo 只是实现了 Nameable 协议)

Any help would be appreciated.任何帮助,将不胜感激。

As fas as I can see and understand this already does what you want.据我所知并理解,这已经可以满足您的需求。

For example when I try例如,当我尝试

y = NameableList[int]

I get the following mypy error:我收到以下 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)

Ie the generic allows Foo because it adheres to the protocol (not because it inherits from Nameable ), but does not allow int because it does not.即泛型允许Foo因为它遵守协议(不是因为它继承自Nameable ),但不允许int因为它没有。

I'm using Python 3.9.2 and mypy==0.812.我正在使用 Python 3.9.2 和 mypy==0.812。 Perhaps you're using an older version which does not support this properly yet?也许您使用的旧版本还不支持此功能?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM