在mypy中,如何指定T
上的类型Generic
具有仅在T
满足某些条件时才有效的方法
例如,如果我们使用min
方法创建了一个自定义集合类,返回集合中最小的元素:
from typing import Generic, TypeVar
T = TypeVar("T")
class MyCollection(Generic[T]):
def __init__(self, some_list: List[T]):
self._storage = some_list
def min(self) -> T: # This requires that T implements __lt__
"Get the smallest element in the collection"
return min(self._storage)
如何告诉类型系统只有在T
实现__lt__
时才允许对MyCollection
的min
进行调用
所以基本上我想让泛型容器的一些方法只有在满足额外协议的情况下才有效
--有用的链接--
您可以从typehints in the standardlib for min中看到,他们已经定义了一个协议来执行__lt__
class SupportsLessThan(Protocol):
def __lt__(self, __other: Any) -> bool: ...
SupportsLessThanT = TypeVar("SupportsLessThanT", bound=SupportsLessThan) # noqa: Y001
在链接的同一存根文件中,查看
list.sort
的类型提示:通过类型暗示
self
,您可以指定一个方法只适用于泛型类的某些专门化。您还可以在mypy文档中看到这个documented因此,您的
min
将被注释为具有合适的
SupportsLessThanT
定义相关问题 更多 >
编程相关推荐