在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__时,才允许在T的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发布于 2020-12-01 19:15:03
在您链接的同一存根文件中,查看list.sort的类型提示
class list(MutableSequence[_T], Generic[_T]):
...
@overload
def sort(self: List[SupportsLessThanT], *, key: None = ..., reverse: bool = ...) -> None: ...
@overload
def sort(self, *, key: Callable[[_T], SupportsLessThan], reverse: bool = ...) -> None: ...通过类型提示self,可以指定方法仅适用于泛型类的某些专门化。您也可以在mypy文档中看到此documented。
因此,您的min将被注释为
def min(self: 'MyCollection[SupportsLessThanT]') -> SupportsLessThanT:
...对SupportsLessThanT有一个合适的定义。
https://stackoverflow.com/questions/65081082
复制相似问题