Support type narrowing on __eq__ with TypeGuard/TypeIs
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Feature
Handle type narrowing when overridden __eq__ method has a return type annotated with TypeIs or TypeGuard.
Pitch
When defining custom __eq__ methods, it might be useful in some contexts to leverage type narrowing. For example, consider an assertion helper[^1] like the following:
import typing
T = typing.TypeVar("T")
class IsInstance(typing.Generic[T]):
def __init__(self, t: type[T]) -> None:
self.t = t
def __eq__(self, other: typing.Any) -> typing.TypeGuard[T]:
return isinstance(other, self.t)
v: typing.Any = 1
assert v == IsInstance(int)
typing.reveal_type(v) # Should ideally be "int"
Currently, mypy doesn't narrow the type. If we explicitly call __eq__, it works as intended:
v: typing.Any = 1
assert IsInstance(int).__eq__(v)
typing.reveal_type(v) # int
[^1]: It's admittedly a bit naive for the sake of the example, but we could imagine more complex stuff.
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 damit, die Logik zur Typverengung für Vergleiche und deren Umgang mit TypeGuard- und TypeIs-Rückgabeannotationen zu lokalisieren. Überprüfe das Verhalten anhand des IsInstance-Beispiels aus dem Issue: Nach assert v == IsInstance(int) sollte reveal_type(v) int melden, entsprechend dem expliziten Aufruf von eq.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- compilers
- Issue-Typ
- Feature
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 45/100