Subclass default overrides more general baseclass type hint
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
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
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne mit den bereitgestellten Vererbungsbeispielen A/B/C und RefA/RefB/RefC und verfolge, wie mypy nicht annotierte Zuweisungen in Unterklassen inferiert. Füge eine Regression-Abdeckung hinzu, die zeigt, dass B.x und RefB.x die ursprünglichen Annotationen der Basisklassen beibehalten, und überprüfe, dass die Zuweisungen auf der dritten Ebene nicht mehr die gemeldeten Inkompatibilitätsfehler erzeugen.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 45/100