Support type narrowing on __eq__ with TypeGuard/TypeIs
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Python
- Estrellas
- 20.6k
- Forks
- 3.3k
- Métricas de merge de PR
- Métricas de PR pendientes
Descripción
Feature
Handle type narrowing when overridden __eq__ method has a return type annotated with TypeIs or TypeGuard.
Pitch
When defining custom __eq__ methods, it might be useful in some contexts to leverage type narrowing. For example, consider an assertion helper[^1] like the following:
import typing
T = typing.TypeVar("T")
class IsInstance(typing.Generic[T]):
def __init__(self, t: type[T]) -> None:
self.t = t
def __eq__(self, other: typing.Any) -> typing.TypeGuard[T]:
return isinstance(other, self.t)
v: typing.Any = 1
assert v == IsInstance(int)
typing.reveal_type(v) # Should ideally be "int"
Currently, mypy doesn't narrow the type. If we explicitly call __eq__, it works as intended:
v: typing.Any = 1
assert IsInstance(int).__eq__(v)
typing.reveal_type(v) # int
[^1]: It's admittedly a bit naive for the sake of the example, but we could imagine more complex stuff.
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
Comienza localizando la lógica de reducción de tipos para las comparaciones y su tratamiento de las anotaciones de retorno TypeGuard y TypeIs. Verifica el comportamiento usando el ejemplo IsInstance del issue: después de assert v == IsInstance(int), reveal_type(v) debería indicar int, coincidiendo con la llamada explícita a eq.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- python
- Área
- compilers
- Tipo de issue
- Nueva funcionalidad
- Dificultad
- 4/5
- Tiempo estimado
- 3-5 días
- Estado de actividad
- Estancado
- Claridad
- Bastante claro
- Aptitud para principiantes
- 45/100