python / python/mypy

Parameter TypeVar unexpectedly becomes optional when unpacking call results

Abierto
#20,219 1 comentario 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

bug topic-type-context
Lenguaje dominante
Python
Estrellas
20.6k
Forks
3.3k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

Bug Report

When calling a generic function mypy unexpectedly introduces optionality in the TypeVar when the result is unpacked and raises an error on a perfectly valid function call:

from typing import Iterable


def fun[T](values: Iterable[T], value: list[T]) -> tuple[T | None, T | None]:
    ...
    return None, None


values: Iterable[int]
my_list: list[int]

result = fun(values, my_list)  # works fine
m, n = result

a, b = fun(values, my_list)  # raises error in mypy

Mypy error:

main.py:15: error: Argument 2 to "fun" has incompatible type "list[int]"; expected "list[int | None]"  [arg-type]

This has something to do with the return type of the function being a tuple of optional T's. If the return type is not a union with None or not a tuple, the error disappears.

To reproduce

Here is playground gist of the example: gist

Expected Behavior

In the example I expect both calls to be approved by mypy. Also, I don't expect unpacking to influence what arguments can given in a function call, at least not in this case.

Actual Behavior

mypy raises an error on the second call.

Your Environment

I used mypy playground to confirm this error in various versions:

  • Mypy version used: 1.17.1 1.18.2 master branch
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.12 3.13 3.14

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 ejemplo mínimo de una función genérica del issue y ejecútalo con mypy usando las versiones y configuraciones de Python indicadas. Rastrea la inferencia de tipos para el desempaquetado de tuplas y los TypeVars opcionales; se considera terminado cuando ambas llamadas se aceptan sin introducir una expectativa incompatible de list[int | None].

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

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.