Wie tippt ich eine "eindeutige" Funktion ein? [Duplikat]
Posted: 20 Aug 2025, 11:18
Ich möchte einen kleinen Alias für sortiert (list (set ()) erstellen. Ich tue: < /p>
Wie geht es?
Code: Select all
from typing import Iterable, TypeVar
H = TypeVar("H")
def unique(x: Iterable[H]) -> list[H]:
return sorted(list(set(x)))
unique(a for a in ["a", "b", "c"])
< /code>
, aber dies schlägt fehl bei: < /p>
main.py:29: error: Value of type variable "SupportsRichComparisonT" of "sorted" cannot be "H" [type-var]
Found 1 error in 1 file (checked 1 source file)
< /code>
OK, also tue ich: < /p>
from abc import ABCMeta, abstractmethod
from typing import Any, Iterable, TypeVar
class ComparableHashable(metaclass=ABCMeta):
@abstractmethod
def __lt__(self, other: Any) -> bool: ...
@abstractmethod
def __hash__(self) -> int:
pass
H = TypeVar("H", bound=ComparableHashable)
def unique(x: Iterable[H]) -> list[H]:
return sorted(list(set(x)))
unique(a for a in ["a", "b", "c"])
< /code>
, aber dies schlägt fehl bei: < /p>
main.py:31: error: Value of type variable "H" of "unique" cannot be "str" [type-var]
Found 1 error in 1 file (checked 1 source file)