python / python/typeshed

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

Open
#9,571 7 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

status: deferred
Dominant language
Python
Stars
5.1k
Forks
2.1k
Avg merge
1d 19h
Merged PRs (30d)
82

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing stdlib/builtins.pyi at the set and frozenset definitions referenced in the issue, along with PR 9570's related mapping changes. Decide how the set type variable and a covariant, Hashable-bounded frozenset variable should be represented, then update the stdlib stubs and verify that unhashable keys or set values are rejected by the relevant type-checking tools.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
developer-experience
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.