python / python/mypy

Allow unsafe overrides in sub-subclasses that are compatible with subclass

Abierto
#12,372 3 comentarios 6 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

feature topic-inheritance
Lenguaje dominante
Python
Estrellas
20.6k
Forks
3.3k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

Feature

When a subclass is implemented with unsafe method override, error can be suppressed with # type: ignore[override] comment. However, further subclassing requires this comment to be present in subclasses too.

Pitch

Suppose we have the following structure:

class A:
    def foo(self) -> int: pass

class B(A):
    def foo(self) -> str: pass  # type: ignore[override]

class C(B):
    def foo(self) -> str: pass

Currently mypy complains:

example.py:8: error: Return type "str" of "foo" incompatible with return type "int" in supertype "A"

But in reality we do expect that all B subclasses should implement foo with signature () -> str. For instance, it is useful when B is replacement for A with slightly different usage (when we don't want to replicate all internal logic - e.g. if it comes from third-party package). It takes care to override all methods that became incompatible after this change, and now B is consistent. Then we want to add some feature to B via subclassing while preserving its interface. All signatures are preserved, but mypy complains that we are incompatible with old base (A). I think that when unsafe override is explicitly ignored once, mypy should check new implementation against definitions in B, not in A, ignoring the fact that B has unsafe overrides. Actually now the checker reports errors that are explicitly ignored: we already took care to ignore that errors inside B.

Real world example: ModelChoiceField in Django inherits from ChoiceField (yeah, that's bad design decision, but I'm working on stubs and can't change the source). Incompatible part:

class ChoiceField(Field):
    def to_python(self, data: Optional[Any]) -> str: ...

class ModelChoiceField(ChoiceField):
    def to_python(self, data: Optional[Any]) -> Optional[Model]: ...  # type: ignore[override]

When end Django user tries to subclass ModelChoiceField and implements to_python with same signature, user receives mypy error. However, this implementation is perfectly valid as long as direct superclass already defines that incompatible change.

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

El issue no nombra archivos fuente ni tests. Empieza reproduciendo el ejemplo A/B/C y sigue la comprobación de overrides de mypy para los métodos de las subclases; se considera terminado cuando el override compatible de C se acepta basándose en B, mientras que la incompatibilidad de B, ignorada explícitamente, sigue suprimida.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
python
Área
devtools
Tipo de issue
Nueva funcionalidad
Dificultad
5/5
Tiempo estimado
Más de una semana
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.