python - How can I hint that a type is comparable with typing -


say want write comparison sorting function, can hint input must sequence sequence[t] (or mutablesequence[t] in case).

from typing import mutablesequence, t  def comparison_sort(s: mutablesequence[t]) -> none:     pass 

however there not seems out-of-the box way hint t must comparable. (there no comparable or ordered or seems in typing.) how can achieve this? avoid specifying specific set of types, int, float, 'str` user hint own type comparable.

as noted in comments, comparable isn't state of being, it's meaningful descriptor pair of types. usually, sorting function working homogeneous types though, long don't mind type checker handling concept of "supports < types" rather "supports < arbitrary types", can define own comparable , bound typing typevar it. conveniently, pep484 (which defines typing hints) provides an example of how you'd this:

from abc import abcmeta typing import any, typevar  class comparable(metaclass=abcmeta):     @abstractmethod     def __lt__(self, other: any) -> bool: ...  ct = typevar('ct', bound=comparable) 

you can use comparable_sort definition with:

def comparable_sort(s: mutablesequence[ct]) -> none: 

note required __lt__ defined; rule, python implements own sorting functions entirely in terms of __lt__ (it doesn't use of other rich comparator operators, not __eq__), it's idea design own algorithm same way, sorted can handle, can handle same way.