python / python/mypy

Type of argument is not inferred for a TypeVar in a Generic type

Abierto
#5,324 2 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

documentation priority-1-normal topic-type-variables topic-usability
Lenguaje dominante
Python
Estrellas
20.6k
Forks
3.3k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

Mypy needs a type annotation for a variable that it could easily infer from the constructor argument annotations. This works perfectly with normal types. But using a TypeVar in a Generic type, somehow it doesn't.

from typing import Generic, TypeVar


class A:
    pass


class B:
    pass


T_Value = TypeVar("T_Value", A, B)


class Guess(Generic[T_Value]):
    def __init__(self, value: T_Value, confidence: float) -> None:
        self.value = value  # <-- line 17
        self.confidence = confidence

Mypy then complains it needs a type annotation

foo.py:17: error: Need type annotation for 'value'

This of course is no big deal since I can just add that annotation:

class Guess(Generic[T_Value]):
    def __init__(self, value: T_Value, confidence: float) -> None:
        self.value: T_Value = value
        self.confidence = confidence

But shouldn't mypy infer the type from the type annotations in the constructor?

If I'm doing something wrong please let me now.
I didn't find a similar issue but if this is a duplicate feel free to close.

I'm using:
Python 3.7.0, mypy 0.610, macOS 10.13.5

Same result with the current master (2018-07-05):
mypy 0.620+dev-f5058bcb269a55b33a02c3e3fd345541839bf06e

Flags I'm using:
strict_optional = true
ignore_missing_imports = true
follow_imports = silent

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

Reproduce el ejemplo de Python inline con la configuración indicada de strict_optional, ignore_missing_imports y follow_imports. Empieza siguiendo la inferencia de mypy para la asignación del atributo Generic TypeVar; se considera terminado cuando el ejemplo ya no requiere una anotación explícita y el comportamiento está cubierto por una prueba de regresión.

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

Evaluación

Stack tecnológico
python
Área
compilers
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.