python / python/mypy

Seemingly erroneous incompatible type "list[int]"; expected "Iterable[Never]"

Open
#16,788 1 comment 12 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
mypy seems to not like an argument of type Union[T, Iterable[T]] where T = TypeVar("T"), instead considering it to be Iterable[Never].

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.12&gist=1471ed0391c1e251edc0ecd85a28d684

from typing import List, Iterable, TypeVar, Union

T = TypeVar("T")

def coerce_list(x: Union[T, Iterable[T]]) -> List[T]:
    reveal_type(x)
    raise NotImplementedError()

def test() -> None:
    coerce_list(1)
    coerce_list([1, 2])

Expected Behavior
I expected no errors. I expected [1, 2] to match Iterable[T] with T = int.

Actual Behavior

example.py:6: note: Revealed type is "Union[T`-1, typing.Iterable[T`-1]]"
example.py:11: error: Argument 1 to "coerce_list" has incompatible type "list[int]"; expected "Iterable[Never]"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

I'm confused why the revealed type of x looks to be correct (although I don't understand the -1 part), but the expected type of the parameter is Iterable[Never].

Your Environment

  • Mypy version used: mypy 1.8.0 (compiled: yes)
  • Mypy command-line flags: (none)
  • Mypy configuration options from mypy.ini (and other config files): (none)
  • Python version used: 3.11.2 (Debian 12)

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 linked mypy-play reproduction, or the shown example.py, with mypy 1.8.0 and current mypy to compare behavior. Trace how generic arguments are inferred for Union[T, Iterable[T]], then verify that both coerce_list(1) and coerce_list([1, 2]) pass without errors.

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
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.