How to restrict asssignment to TypeVar to Hashable?
Question:
I want to restrict TypeVar
role to Hashable
.
For example,
def convert_to_set(x: List[T]) -> Set[T]:
return set(x)
I want to indicate that T
is subclass of Hashable
, because all elements of set must be hashable.
One of the solution I thought is the following:
TH = TypeVar("TH", Hashable, Hashable)
However, I think this is ugly.
What should I do?
Answers:
I found a solution from https://mypy.readthedocs.io/en/stable/generics.html#type-variables-with-upper-bounds
T = TypeVar(T, bound=Hashable)
I want to restrict TypeVar
role to Hashable
.
For example,
def convert_to_set(x: List[T]) -> Set[T]:
return set(x)
I want to indicate that T
is subclass of Hashable
, because all elements of set must be hashable.
One of the solution I thought is the following:
TH = TypeVar("TH", Hashable, Hashable)
However, I think this is ugly.
What should I do?
I found a solution from https://mypy.readthedocs.io/en/stable/generics.html#type-variables-with-upper-bounds
T = TypeVar(T, bound=Hashable)