python / python/mypy

mypy accepts invalid PEP 604 syntax with forward reference

Abierto
#14,397 1 comentario 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

feature topic-pep-604 topic-runtime-semantics
Lenguaje dominante
Python
Estrellas
20.6k
Forks
3.3k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

Bug Report

PEP 604 introduced the | syntax, however it's not entirely equivalent to the Union syntax. Forward references with | are not supported and result in TypeErrors TypeError: unsupported operand type(s) for |: 'type' and 'str'. Mypy doesn't warn the user about this and accepts | with forward references.

To Reproduce

T = list[int | "T"]

Playground

Expected Behavior

Some kind of error telling me that this syntax is not supported.

Actual Behavior

No errors reported.

Your Environment

  • Mypy version used: 0.991
  • Mypy command-line flags: --strict or no flags, doesn't matter
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.11

I originally raised this as a discussion in pyright repo. And since then pyright has implemented https://github.com/microsoft/pyright/commit/6eb846709f4fec0180593f3e89f1dd5b20f41956 to detect this incorrect usage of | (available in release 1.1.285). I have to admit that documentation on this is a bit murky as I was expecting | to be equivalent to Union and I wasn't the only one, see https://github.com/python/cpython/issues/90015. From what I can gather in this CPython issue runtime won't be changed to make this syntax valid and docs should be changed instead (but neither happened yet).

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

Empieza ejecutando mypy en el reproducer proporcionado, T = list[int | "T"], y sigue cómo se analizan las referencias adelantadas en las uniones PEP 604. Añade una prueba de regresión para este ejemplo y asegúrate de que mypy indique que la sintaxis no es compatible, preservando al mismo tiempo el manejo de uniones válidas.

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
Bastante claro
Aptitud para principiantes
42/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.