How can I hint that a type is comparable with typing

前端 未结 2 1939
無奈伤痛
無奈伤痛 2021-01-04 23:31

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

2条回答
  •  無奈伤痛
    2021-01-05 00:14

    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.

提交回复
热议问题