python / python/mypy

mypy shows a somewhat confusing error message for functions returning a TypeVar value

Abierto
#15,724 7 comentarios 0 reacciones 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

Not sure if this should be considered a bug, or an enhancement proposal...

I had some code looking like this:

CallbackResult = TypeVar("CallbackResult")
VisitCallback = Callable[[str], Optional[CallbackResult]]

def visititems(self, func: VisitCallback) -> CallbackResult:
    return func("test")

Actual Behavior

mypy says about this code:

error: A function returning TypeVar should receive at least one argument containing the same TypeVar  [type-var]

Expected Behavior

First, I was confused, and thought that mypy is not able to infer that CallbackResult is hidden in the function input as the return value of VisitCallback. Actually I was initially going to open an issue because of that.

Then I noticed that in a sense, mypy is correct - because I spotted that VisitCallback returns Optional[CallbackResult], while the visititems function returns a CallbackResult.

Once I fixed that, the error went away. But in this case, mypy did not really "pinpoint" the problem as well as I feel it could.

Not sure how deeply mypy plays out the type algebra to figure out what types are constructible in a context, but I feel like this specific case could be a rather "common" one (forgetting the Optional), so maybe this can be catched with a better error message.

Maybe something of the form "the function returns typevar value X, but based on its inputs can only construct Y[X, ...]" could be possible? So that it would cover Optional, Union and other simple cases like List, etc.

Your Environment

  • Mypy version used: 1.1.1

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 reproduciendo el ejemplo de TypeVar del issue y examinando cómo mypy informa del error de type-var cuando se devuelve Optional[CallbackResult] como CallbackResult. Se considera terminado cuando se produzca un diagnóstico más claro que explique la discrepancia y cubra wrappers simples como Optional, Union o List.

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

Evaluación

Stack tecnológico
python
Área
compilers, devtools
Tipo de issue
Nueva funcionalidad
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.