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?

Asked By: tamuhey

||

Answers:

I found a solution from https://mypy.readthedocs.io/en/stable/generics.html#type-variables-with-upper-bounds

T = TypeVar(T, bound=Hashable)
Answered By: tamuhey
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.