Say I want to write a comparison sorting function, I can hint that the input must be a sequence with Sequence[T]
(or MutableSequence[T]
in this cas
This version works with the current mypy
version.
Based on the thread in the typing
repo: https://github.com/python/typing/issues/59
from __future__ import annotations
from abc import abstractmethod
from typing import MutableSequence, Protocol, TypeVar
class Comparable(Protocol):
"""Protocol for annotating comparable types."""
@abstractmethod
def __lt__(self: CT, other: CT) -> bool:
pass
CT = TypeVar("CT", bound=Comparable)
def comparison_sort(s: MutableSequence[CT]) -> None:
pass
comparison_sort([1, 2, 3]) # OK
comparison_sort([1.0, 2.0, 3.0]) # OK
comparison_sort(["42", "420", "2137"]) # OK
comparison_sort([1, 2, "3"]) # mypy error
link to Github gist.