python / python/mypy

Support type narrowing on __eq__ with TypeGuard/TypeIs

Aperta
#20,779 1 commento 1 reazione 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

feature topic-type-narrowing topic-typeguard-typeis
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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.

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia individuando la logica di restringimento dei tipi per i confronti e la relativa gestione delle annotazioni di ritorno TypeGuard e TypeIs. Verifica il comportamento usando l'esempio IsInstance dell'issue: dopo assert v == IsInstance(int), reveal_type(v) dovrebbe riportare int, in corrispondenza della chiamata esplicita a eq.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
compilers
Tipo di issue
Funzionalità
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
45/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.