python / python/mypy

List constant expression treated differently to list literal

Offen
#21,710 2 Kommentare 0 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

When assigning a list literal to a variable with a known type, mypy uses that type in inferring the type of the list literal. This gives the appearance that invariance is relaxed e.g.

x: list[int | None] = [0, 1, 2, 10]  # ok

is accepted even though normally a list[int] cannot be assigned to a list[int | None].

However, when the list literal is written as a more complex expression, that stops working:

x: list[int | None] = [0, 1, 2] + [10]  # error

That's obviously a bit contrived. My actual use case is more similar to this:

x: list[int | None] = [i for i in range(3)] + [10]  # error

Maybe this isn't fixable - it's only sound because list.__add__ returns a new list which has no other references, but I don't think there is a way to represent that in typeshed.

To Reproduce

x: list[int | None] = [0, 1, 2] + [10]

Expected Behavior

No error

Actual Behavior

concat2.py:1: error: Incompatible types in assignment (expression has type "list[int]", variable has type "list[int | None]")  [assignment]
concat2.py:1: note: "list" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance
concat2.py:1: note: Consider using "Sequence" instead, which is covariant

Your Environment

  • Mypy version used: 2.2.0
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.12.3

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

In diesem Issue ist weder eine Implementierungsdatei noch ein Test angegeben. Beginne damit, die gemeldete Zuweisung mit mypy zu reproduzieren, und verfolge dann, wie List-Literale, Listenkonkatenation und Comprehensions inferiert und gegen die annotierte Variable geprüft werden. Erledigt ist die Aufgabe, wenn die gemeldeten Konkatenationsfälle bestehen, ohne die gewöhnlichen Invarianzprüfungen von Listen abzuschwächen.

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
Ruhig
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
52/100

Neue Issues direkt in Ihr Postfach

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