python / python/mypy

Faulty type narrowing with value restrictions

Abierto
#13,083 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

bug topic-type-variables
Lenguaje dominante
Python
Estrellas
20.6k
Forks
3.3k
Merge medio
1 d 18 h
PR fusionados (30 d)
54

Descripción

Bug Report

When passing an empty list directly into a value restricted generic function, the inferred return type can end up being too narrow.

To Reproduce

from typing import TypeVar


TV = TypeVar("TV", str, int)


def foo(x: list[TV]) -> list[TV]:
    return x
    

# Should be: builtins.list[builtins.str] | builtins.list[builtins.int]
reveal_type(foo([]))  # "builtins.list[builtins.str]"

https://mypy-play.net/?mypy=latest&python=3.10&flags=strict&gist=129ba2fed0c6ba1a861149f944db3420

Expected Behavior

I would expect the revealed type to either be builtins.list[builtins.str] | builtins.list[builtins.int].

Alternatively, having this result in an error of some sort would be fine. As a reference, when assigning the empty list first, it becomes a list[Any] instead of a list[<nothing>]. This results in the revealed type being list[Any], but also an error along the lines of Need type annotation for "l" (hint: "l: List[<type>] = ...").

Actual Behavior

The revealed type was builtins.list[builtins.str]

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 el caso reproducible de mypy-play enlazado y rastrea el tratamiento de los argumentos de listas vacías durante la inferencia de un TypeVar restringido por valores. Compara el tipo inferido con la unión esperada y con el comportamiento de diagnóstico aceptable descrito en el issue. Se considera terminado cuando el ejemplo ya no se restringe incorrectamente a list[str].

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
Bien especificado
Aptitud para principiantes
45/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.