List constant expression treated differently to list literal
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 20.6k
- Fork
- 3.3k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
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
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Nell’issue non sono indicati né un file di implementazione né un test. Inizia riproducendo l’assegnazione segnalata con mypy, quindi traccia come vengono inferiti e verificati rispetto alla variabile annotata i letterali di lista, la concatenazione di liste e le comprehension. Il lavoro è completato quando i casi di concatenazione segnalati passano senza indebolire i normali controlli di invarianza delle liste.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- compilers, devtools
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Tranquilla
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 52/100