python / python/mypy

Generic `NamedTuple` does appear attribute-less in `match` statements, and member type information is erased

Abierto
#21,050 1 comentario 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

Bug Report

If a NamedTuple is generic over T, then for some reason, inside a match statement over this NamedTuple, all information about member variables and their types are erased. Even if they are explicitly stated.

To Reproduce

from typing import NamedTuple

class Wrapper[T](NamedTuple):
    wrap: T


foo: Wrapper[int] = Wrapper(123)

def bar() -> int:
    match foo:
        case Wrapper(wrap=w):
            return w
        case _:  # this is only to make this error-less with `pyrefly`
            raise RuntimeError("Unreachable")

Expected Behavior

This function clearly matches a Wrapper[int] in its first case. It should detect it can match the internal wrap variable, and it also has to be int.

$ pyrefly check tst.py
 INFO 0 errors
$ pyright tst.py
0 errors, 0 warnings, 0 informations

Actual Behavior

mypy for some reason seems to say that Wrapper does not even have a wrap attribute, and also, it's saying that this is Any, even though the matched Wrapper here is Wrapper[int].

$ mypy --strict tst.py
tst.py:12: error: Class "tst.Wrapper[Any]" has no attribute "wrap"  [misc]
tst.py:13: error: Returning Any from function declared to return "int"  [no-any-return]

Your Environment

  • Mypy version used: 1.19.1
  • Mypy command-line flags: --strict
  • Python version used: 3.12.9

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 informe en tst.py usando Python 3.12.9 y mypy --strict; después, compara el resultado con pyrefly y pyright como se muestra. Rastrea cómo se analiza el patrón genérico NamedTuple en la instrucción match; se considera terminado cuando w se reconoce como el atributo wrap con tipo int y el ejemplo no informa de errores.

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
3/5
Tiempo estimado
1-2 días
Estado de actividad
Estancado
Claridad
Bien especificado
Aptitud para principiantes
48/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.