python / python/mypy

Set and Dict generalizing the type unnecessarily

Open
#17,238 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

See these two example functions:

def f(items: list[str] | list[int]) -> None:
    items_as_set: set[str] | set[int] = set(items)

def g(key_to_count: dict[str, float] | dict[int, float]) -> None:
    key_to_count_2: dict[str, float] | dict[int, float] = {k: v for k, v in key_to_count.items()}

Mypy 1.10.0 complains about the assignment in each of them:

test_mypy_dict.py:2: error: Incompatible types in assignment (expression has type "set[object]", variable has type "set[str] | set[int]")  [assignment]
test_mypy_dict.py:5: error: Incompatible types in assignment (expression has type "dict[str | int, float]", variable has type "dict[str, float] | dict[int, float]")  [assignment]

To Reproduce

Playground gist: https://mypy-play.net/?mypy=latest&python=3.12&gist=83bde5f3f11470e94b6a680158649641

Expected Behavior

The set() or dict() operation applied on a variable that is either a list[str] | list[int] is always either a set[str] or set[int]. The same applies to function g using a dict. Thus the functions should not raise a mypy error.

Workarounds

I tried two workarounds:

  • Using a mixed type of list[str | int]. However, I get the type list[str] | list[int] by an external function, thus this is not compatible.
  • Using a generic. This is not working either.

See the playground gist: https://mypy-play.net/?mypy=latest&python=3.12&gist=264490179628a0a214a2e5bd947b8ccf
image

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 running the two Python reproductions from the issue, including the linked mypy-play examples, and compare the inferred types and assignment errors for set() and the dict comprehension. Trace the type-checking path for these constructor and comprehension expressions; done means both functions type-check without errors while preserving the union of homogeneous container types.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, devtools
Issue type
Bug
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.