python / python/mypy

Parameter TypeVar unexpectedly becomes optional when unpacking call results

Offen
#20,219 1 Kommentar 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

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

Beschreibung

Bug Report

When calling a generic function mypy unexpectedly introduces optionality in the TypeVar when the result is unpacked and raises an error on a perfectly valid function call:

from typing import Iterable


def fun[T](values: Iterable[T], value: list[T]) -> tuple[T | None, T | None]:
    ...
    return None, None


values: Iterable[int]
my_list: list[int]

result = fun(values, my_list)  # works fine
m, n = result

a, b = fun(values, my_list)  # raises error in mypy

Mypy error:

main.py:15: error: Argument 2 to "fun" has incompatible type "list[int]"; expected "list[int | None]"  [arg-type]

This has something to do with the return type of the function being a tuple of optional T's. If the return type is not a union with None or not a tuple, the error disappears.

To reproduce

Here is playground gist of the example: gist

Expected Behavior

In the example I expect both calls to be approved by mypy. Also, I don't expect unpacking to influence what arguments can given in a function call, at least not in this case.

Actual Behavior

mypy raises an error on the second call.

Your Environment

I used mypy playground to confirm this error in various versions:

  • Mypy version used: 1.17.1 1.18.2 master branch
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.12 3.13 3.14

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

Beginne mit dem minimalen Beispiel einer generischen Funktion im issue und führe es mit den gemeldeten Python-Versionen und Konfigurationen gegen mypy aus. Verfolge die Typinferenz für das Entpacken von Tupeln und optionale TypeVars; fertig ist die Aufgabe, wenn beide Aufrufe akzeptiert werden, ohne eine inkompatible Erwartung von list[int | None] einzuführen.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

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

Neue Issues direkt in Ihr Postfach

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