python / python/mypy

Subclass default overrides more general baseclass type hint

Abierto
#11,897 1 comentario 2 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

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

Descripción

Bug Report

When a base class field has a general type hint (eg: Union[int, str] or a base class) and a subclass sets a default without a type hint, the field's type hint is narrowed to the specific default value's type rather than maintaining the original base class's hint. This prevents a second-order subclass from setting a new default with a different type that would otherwise align with the originally specified hint on the first class.

This is particularly relevant when using something like dataclasses or pydantic.

To Reproduce

from typing import Union

class A:
    x: Union[int, str] = 5

class B(A):
    x = 5

class C(B):
    # error: Incompatible types in assignment (expression has type "str", base class "B" defined the type as "int")
    x = "5"

class RefA:
    x: A

class RefB(RefA):
    x = B()

class RefC(RefB):
    # error: Incompatible types in assignment (expression has type "A", base class "RefB" defined the type as "B")
    x = A()

Expected Behavior

The B.x and RefB.x fields to maintain their base classes type hint rather than implicitly narrow to the default value's type. Thus, C.x and RefC.x fields to support values matching the first base class's type hint.

Actual Behavior

The middle subclasses implicitly narrow the type hint to type(default_value) so a new default on a third subclass must match that, rather than the original explicit hint.

Your Environment

  • Mypy version used: 0.930
  • Mypy command-line flags: n/a
  • Mypy configuration options from mypy.ini (and other config files): n/a
  • Python version used: 3.9.7
  • Operating system and version: macos 12.0.1

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

Comienza con los ejemplos de herencia proporcionados A/B/C y RefA/RefB/RefC y sigue cómo mypy infiere las asignaciones no anotadas en las subclases. Añade cobertura de regresión que muestre que B.x y RefB.x conservan las anotaciones originales de las clases base, y verifica que las asignaciones del tercer nivel ya no produzcan los errores de incompatibilidad reportados.

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

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.