Skip to content

Add bound Hashable for types for keys of type Mapping and values of type Set #9571

Open
@kruvasyan

Description

@kruvasyan

Problem

Types used for keys in mappings and values in sets are too broad.

How to reproduce

d: [list, int] = {}  # Tools that use typeshed see this code as valid.
d[[1]] = 2 # TypeError: unhashable type: 'list'

Solution

Change type of keys in mappings: _KT = TypeVar("_KT") to _KT = TypeVar("_KT", bound=Hashable)

  • Added PR with fixes to stdlib

But I still have questions about how to fix the types in set and frozenset.

  • For set, we using _T, which is also used for values in the list. Can I change it to _KT? The requirements for the type of values in the set are the same as for the keys in the dictionary. I understand that it is a value, not a key, and the name can be confusing. Do you think of a better option?

  • For frozenset, we using covariant _T_co, which is also used for values in the tuple. It's the same problem here. We need a new type that is covariant and bound to Hashable.

  • set

  • frozenset

And once we figure out what to do with types in stdlib, I will be happy to add the same changes to third-party libraries.

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: deferredIssue or PR deferred until some precondition is fixed

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions