Jean-Francois T.
Jean-Francois T.

Reputation: 12920

What is the type of immutable object in Python (for mypy)

I always use mypy in my Python programs.

What is the type (from typing) for immutable objects, the ones that could be used for a dictionary key?

To put back into context, I want to write a class inherited from dictionary and I have the following code

class SliceableDict(dict):
    def __getitem__(self, attr:Any) -> Any:
        return super().__getitem__(attr)

Type hints in that case are pretty useless, isn't it?

Thanks

Upvotes: 8

Views: 3256

Answers (2)

ShadowRanger
ShadowRanger

Reputation: 155353

typing.Hashable refers to any type that can serve as a valid key in a dict or value in a set.

It doesn't require true immutability (any object can define __hash__), but in general, hashable things should be things that are "treated as immutable", since it will break things should they be mutated after insertion into a set or after being inserted as a dict key.

Upvotes: 7

jwodder
jwodder

Reputation: 57470

The keys of a dict are hashable (see the first sentence of the docs on dict), and the hashable type is typing.Hashable, an alias for collections.abc.Hashable.

Upvotes: 13

Related Questions