Type narrowing in while loop
Offen
Dieses Issue hat noch niemand übernommen.
feature
topic-type-narrowing
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Feature
example.py
from __future__ import annotations
import typing as t
class Node:
parent: Node | None = None
N = t.TypeVar("N", bound=Node)
def find_ancestor(node: Node, node_type: t.Type[N]) -> N | None:
ancestor = node.parent
while ancestor and not isinstance(ancestor, node_type):
ancestor = ancestor.parent
return ancestor
mypy 1.0.1 errors with:
example.py:13: error: Incompatible return value type (got "Optional[Node]", expected "Optional[N]") [return-value]
Would be great to narrow the type to N here and avoid the spurious error.
Pitch
Type narrowing in a while loop would improve inference. pyright already does this.
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
Führe zunächst mypy gegen die bereitgestellte example.py aus und reproduziere den Fehler beim Rückgabewert. Untersuche anschließend den Kontrollfluss zur Typverengung für while-Schleifen und vergleiche das Verhalten mit pyright. Erledigt ist die Aufgabe, wenn die Schleife den Wert nach isinstance auf N verengt und das Beispiel den Fehler nicht mehr meldet.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Feature
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 45/100