In mypy, how would you specify that a type Generic
over T
has methods that are only valid if T
meets certain conditions?
For example, if we made a custom collection class with a min
method, returning the smallest element in the collection:
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)
How can you tell the type system that calling min
on MyCollection
of T
is only allowed if T
implements __lt__
?
So basically I'd like to have some methods of a generic container only be valid if extra protocols are met.
-- Useful links --
You can see from the typehints in the standardlib for min that they've defined a protocol for enforcing __lt__
is implemented
class SupportsLessThan(Protocol):
def __lt__(self, __other: Any) -> bool: ...
SupportsLessThanT = TypeVar("SupportsLessThanT", bound=SupportsLessThan) # noqa: Y001