Python和mypy:基于协议使用typebound创建泛型集合

Python和mypy:基于协议使用typebound创建泛型集合,python,python-3.x,mypy,structural-typing,Python,Python 3.x,Mypy,Structural Typing,我想创建一个泛型容器类,其中类型的边界基于实现协议,如下所示: class Nameable(Protocol): def name(self) -> str: ... T = TypeVar("T", bound=Nameable) class NameableList(Generic[T]): ... class Foo: _name: str def name(self) -> str:

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

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=namablelist[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。也许您使用的是一个旧版本,它还不能正确支持这一点?

我刚刚意识到绑定强制执行子类型要求。这仍然保留了我最初的问题-我们如何在泛型类型上强制协议约束?我在您的代码中没有看到任何mypy错误。是的,这是有效的-我自己的代码中有一些其他问题导致了问题。