python / python/mypy

Args with a generic type will use the mother type, rather than a literal

Abierto
#17,090 1 comentario 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

bug topic-join-v-union
Lenguaje dominante
Python
Estrellas
20.6k
Forks
3.3k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

Bug Report
Args with a generic type will use the mother type, rather than a literal

I noticed this issue while trying to chain together two lists with different types with itertools.chain.

To Reproduce

from typing import TypeVar

T = TypeVar('T')

class M:
    pass


class C1(M):
    def my_method(self) -> None:
        pass

class C2(M):
    def my_method(self) -> None:
        pass


def test(*args: T) -> T:
    return args[0]

result = test(C1(), C2())
result.my_method()

https://mypy-play.net/?mypy=latest&python=3.12&flags=strict&gist=d78c6875b87a3040126e1926b8f7ba0c

Expected Behavior
I expected to be able to run my_method, as all arguments have it defined. Instead the mother type is used. This issue can be mitigated by extracting the arguments, giving them a literal type, then unpack them into the function:

my_args: list[C1 | C2] = [C1(), C2()]
test(*my_args)

Actual Behavior

main.py:26: error: "M" has no attribute "my_method"  [attr-defined]

I believe this happens because untyped lists defined with items will use the mother type of all items. I don't think this is very intuitive for args.

Visual Studio Code's Pylance does not give an error in this situation, even with the strict flag.

Your Environment

  • Mypy version used: 1.9.0
  • Mypy command-line flags: no flags
  • Mypy configuration options from mypy.ini (and other config files): no config
  • Python version used: 3.9, 3.10, 3.11, 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 ejecutando la reproducción proporcionada de mypy-play con las versiones indicadas de Python y mypy; después, sigue la inferencia de argumentos genéricos para el ejemplo test(*args: T) -> T. Se considera terminado cuando la llamada con una combinación de C1 y C2 se infiere como un tipo que expone my_method sin requerir la lista anotada intermedia, con cobertura de regresión para este comportamiento.

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
42/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.