python / python/mypy

False positive when assigning bounded generic to union including the bound

Open
#20,516 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

The following example is type-safe, but mypy reports 6 false positives:

def upcast(arg: int) -> int:
    return arg

def test[X: int](items: list[X]) -> list[X]:
    _a: list[int] = list(items)           # ✅️
    _b: list[int] = [*items]              # ✅️
    _c: list[int] = [x for x in items]    # ✅️

    _1: list[str] | list[int] = list(items)         # ❌️
    _2: list[int] | list[str] = list(items)         # ❌️
    _3: list[str] | list[int] = [*items]            # ❌️
    _4: list[int] | list[str] = [*items]            # ❌️
    _5: list[str] | list[int] = [x for x in items]  # ❌️
    _6: list[int] | list[str] = [x for x in items]  # ❌️
    _7: list[str] | list[int] = [upcast(x) for x in items]  # ✅️
    _8: list[int] | list[str] = [upcast(x) for x in items]  # ✅️
    return items

context: https://github.com/python/mypy/pull/20419#discussion_r2658824097

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 with the linked mypy playground and reproduce the bounded-generic example, comparing its six diagnostics with the other type checkers. Done means the six union assignments are accepted without changing the existing accepted cases or introducing new errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.