Wie tippt ich eine "eindeutige" Funktion ein? [Duplikat]Python

Python-Programme
Anonymous
 Wie tippt ich eine "eindeutige" Funktion ein? [Duplikat]

Post by Anonymous »

Ich möchte einen kleinen Alias für sortiert (list (set ()) erstellen. Ich tue: < /p>

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)
Wie geht es?

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post