Subclass default overrides more general baseclass type hint
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 20.6k
- Fork
- 3.3k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
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
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia con gli esempi di ereditarietà forniti A/B/C e RefA/RefB/RefC e traccia il modo in cui mypy inferisce le assegnazioni non annotate nelle sottoclassi. Aggiungi una copertura di regressione che mostri che B.x e RefB.x mantengono le annotazioni originali delle classi base, e verifica che le assegnazioni al terzo livello non producano più gli errori di incompatibilità segnalati.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- devtools
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 45/100