python / python/mypy

Get rid of the "flipping behaviour" in narrowign by equality/identity

Aperta
#21,365 3 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

needs discussion topic-type-narrowing
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

We have this code that makes sure that if the intersection of declared and narrowed is not representable, then we prefer the narrowed. I added this logic a while ago, since this is what a user usually expects in case of e.g. an assignment or even an isinstance() check.

However, the recent effort to make equality/identity narrowing symmetric also caused this to result in a "flipping" behavior, when sides exchange types after a comparison, see e.g. testNarrowGenericCallableEquality. Although such cases are rare, I think the resulting behavior is really weird/confusing.

So I propose to add a flag to each restriction in binder (similar to from_assignment), say prefer_declared that would be set to True for right-most operand in equality/identity. This flag would override the fallback mentioned above. So that after something like assert x == y == a, the type of a will not change if the intersection is not representable.

I understand this breaks the symmetry, but this is purely practical thing, this is why people write x == 2 and not 2 == x.

cc @hauntsaninja

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 dalla logica di fallback in mypy/checkexpr.py intorno alle righe 6494-6499, quindi segui come le restrizioni vengono rappresentate e applicate nel binder. Esegui il caso testNarrowGenericCallableEquality per riprodurre il comportamento di inversione e ispeziona i test vicini di narrowing dell’uguaglianza/dell’identità. Il lavoro è completato quando l’operando più a destra mantiene il tipo dichiarato quando l’intersezione non è rappresentabile, senza modificare il normale comportamento di narrowing.

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

Valutazione

Stack tecnologico
python
Ambito
compilers, devtools
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Attiva
Chiarezza
Abbastanza chiara
Idoneità per principianti
48/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.