False positive list comprehension for union type source iterable
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Python
- Estrellas
- 20.6k
- Forks
- 3.3k
- Métricas de merge de PR
- Métricas de PR pendientes
Descripción
Bug Report
MyPy incorrectly asses the type of list comprehensions built from union types. I can't see a way to make this pass typing checks. This and it even affects TypeVar. My only option is a # type: ignore.
The problem arises where a variable foo has a type of Iterable[Bar] | Iterable[Baz] and this is then used as part of a list comprehension [v for v in foo]. MyPy incorrectly evaluates the list comprehension as list[Bar | Baz] not list[Bar] | list[Baz].
I had thought passing a TypeVar might be a simple work around, but it appears the TypeVar is stripped off and only it's binding is maintained.
To Reproduce
I ran into this with code like this:
from typing import TypeVar
class Foo:
item_id: str
class Bar:
item_id: str
class FooWrapper:
items: list[Foo]
class BarWrapper:
items: list[Bar]
_T = TypeVar('_T', bound=FooWrapper | BarWrapper)
def filter_this(value: _T, filter_val: str) -> None:
# Mypy Error on this line 👇
value.items = [item for item in value.items if item.item_id == filter_val]
With the MyPy error:
error: Incompatible types in assignment (expression has type "list[Foo | Bar]", variable has type "list[Foo] | list[Bar]") [assignment]
Found 1 error in 1 file (checked 1 source file)
Expected Behavior
A list comprehension formed from iterable Iterable[Foo] | Iterable[Bar] should have type list[Foo] | list[Bar]
Actual Behavior
A list comprehension formed from iterable Iterable[Foo] | Iterable[Bar] is assessed as having type list[Foo | Bar]
Your Environment
- Mypy version used: mypy 1.11.2 (compiled: yes)
- Mypy command-line flags:
- Mypy configuration options from
mypy.ini(and other config files): - Python version used: python 3.11
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
Empieza ejecutando el reproductor proporcionado de TypeVar y union-iterable con mypy 1.11.2; después, sigue la inferencia de tipos de las comprensiones de listas y el tratamiento de las fuentes de unión. Añade cobertura de regresión que demuestre que la comprensión conserva la unión de los tipos de lista, incluido el caso de TypeVar, y verifica que el error de asignación informado se haya resuelto.
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
- 48/100