Type narrowing of `TypeVar` with abstract bases classes causes `[return-value]` error
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
I'd like to take the case of #15151 two steps further. Instead of dealing with a plain generic type, let's consider the use of a Generic in combination with inheritance.
Bug Report
mypy reports a type incompatibility error when the TypeVars are narrowed within a generic function but the generic arg is not changed in any way.
To Reproduce
import abc
from typing import TypeVar
T = TypeVar("T")
class Base[T](abc.ABC):
@abc.abstractmethod
def foo(self) -> T: ...
class Foo(Base[str]):
def foo(self) -> str:
return "foo"
def foo(o: Base[T]) -> T:
if isinstance(o, Foo):
return o.foo()
return o.foo()
if __name__ == "__main__":
foo(Foo())
Expected Behavior
No errors are thrown since the parameterization of the TypeVar happens via the subclass. During type narrowing, the narrowed type should be considered in both places: the argument and return value.
Actual Behavior
scratch.py:20: error: Incompatible return value type (got "str", expected "T") [return-value]
Your Environment
- Mypy version used: 1.17.0
- Mypy command-line flags: None
- Mypy configuration options from
mypy.ini(and other config files): None - Python version used: 3.12
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 eseguendo il riproduttore scratch.py fornito con mypy 1.17.0 e conferma l’errore [return-value]. Traccia il restringimento dei tipi e la gestione generica del valore restituito coinvolti nel ramo isinstance(o, Foo), quindi aggiungi un test di regressione per questo esempio. Il lavoro è completato quando il test passa senza l’errore [return-value] incompatibile e i test esistenti continuano a passare.
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