python / python/mypy

Can't assign result of list addition to list variable covariantly

Abierto
#16,773 0 comentarios 1 reacción 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

bug
Lenguaje dominante
Python
Estrellas
20.6k
Forks
3.3k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

Bug Report

I cannot assign a list[int] to a list[int | None] if I make it using addition. However, it works fine if I don't use addition. See the tiny example below.

In this example, of course, I can avoid the problem using the list literal [1, 2], but in the application code where I'm facing this issue I actually need to add two comprehensions and store the result as a variable. It shows the same unexpected behavior.

To Reproduce

a: list[int | None] = [1]         # allowed
b: list[int | None] = [1] + [2]   # not allowed

https://mypy-play.net/?mypy=latest&python=3.12&gist=800cfe12c8689a108440e71e641ad240

Expected Behavior

I expect mypy to behave in one of two ways:

  • Both lines are allowed 👈 this would be very convenient
  • Both lines are not allowed 👈 this would be correct
    • How can the first line be allowed if list is invariant?
    • In this case I would need a way to type-hint a list comprehension

Note:

I expect both lines to be treated the same way. This expectation is reinforced because reveal_type([1]) reports the same type as reveal_type([1] + [2]). If that was not the case the different treatment would be easier to understand.

Actual Behavior

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

Your Environment

  • Mypy version used: 1.8.0 and 1.5.1 (latest and version in use on my project)
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.12

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza con la reproducción mínima en main.py y ejecútala con el ejemplo de mypy-play enlazado usando las versiones de Python y mypy indicadas. Traza cómo se infieren las expresiones de literales de lista y de suma de listas, y luego haz que su comportamiento de asignación sea coherente, preservando la invariancia de las listas; añade o actualiza una prueba de regresión para ambas formas.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
python
Área
devtools
Tipo de issue
Error
Dificultad
4/5
Tiempo estimado
3-5 días
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.