Immutable hashable list with correct typings

175 views Asked by At

I need to use sequence of items as dict key and to feat List[...] type. If I use tuple, than it does not feat to a List[...] type and I cannot use Tuple[...] type, because tuple length is not known.

Is there any class (maybe from a 3rd party package) to be like hashable frozen list?

2

There are 2 answers

0
Jasmijn On BEST ANSWER

The immutable equivalent to List[T] is Tuple[T, ...].

From the Python documentation:

To specify a variable-length tuple of homogeneous type, use literal ellipsis, e.g. Tuple[int, ...]. A plain Tuple is equivalent to Tuple[Any, ...], and in turn to tuple.

0
Yaroslav Kishchenko On

It appeared that frozenlist package have needed functionality

    def __hash__(self):
        if self._frozen:
            return hash(tuple(self))
        else:
            raise RuntimeError("Cannot hash unfrozen list.")

But this code is not included in any release (1.0.0 and 1.0.0a0 for that moment). Check if the situation will be improved. Here is the issue I created.