python / python/mypy

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

Offen
#16,788 1 Kommentar 12 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

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)

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Führe zunächst die verlinkte mypy-play-Reproduktion oder das gezeigte example.py mit mypy 1.8.0 und der aktuellen mypy-Version aus, um das Verhalten zu vergleichen. Verfolge, wie generische Argumente für Union[T, Iterable[T]] abgeleitet werden, und verifiziere anschließend, dass sowohl coerce_list(1) als auch coerce_list([1, 2]) ohne Fehler durchlaufen.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
compilers, devtools
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
45/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.