python / python/mypy

Get rid of the "flipping behaviour" in narrowign by equality/identity

Abierto
#21,365 3 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

needs discussion topic-type-narrowing
Lenguaje dominante
Python
Estrellas
20.6k
Forks
3.3k
Merge medio
1 d 18 h
PR fusionados (30 d)
54

Descripción

We have this code that makes sure that if the intersection of declared and narrowed is not representable, then we prefer the narrowed. I added this logic a while ago, since this is what a user usually expects in case of e.g. an assignment or even an isinstance() check.

However, the recent effort to make equality/identity narrowing symmetric also caused this to result in a "flipping" behavior, when sides exchange types after a comparison, see e.g. testNarrowGenericCallableEquality. Although such cases are rare, I think the resulting behavior is really weird/confusing.

So I propose to add a flag to each restriction in binder (similar to from_assignment), say prefer_declared that would be set to True for right-most operand in equality/identity. This flag would override the fallback mentioned above. So that after something like assert x == y == a, the type of a will not change if the intersection is not representable.

I understand this breaks the symmetry, but this is purely practical thing, this is why people write x == 2 and not 2 == x.

cc @hauntsaninja

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 con la lógica de fallback en mypy/checkexpr.py alrededor de las líneas 6494-6499 y luego sigue cómo se representan y aplican las restricciones en el binder. Ejecuta el caso testNarrowGenericCallableEquality para reproducir el comportamiento de inversión e inspecciona las pruebas cercanas de narrowing de igualdad/identidad. Se considera terminado cuando el operando situado más a la derecha conserva su tipo declarado cuando la intersección no se puede representar, sin cambiar el comportamiento habitual de narrowing.

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
Error
Dificultad
4/5
Tiempo estimado
3-5 días
Estado de actividad
Activo
Claridad
Bastante claro
Aptitud para principiantes
48/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.