python / python/mypy

Plugin interface for type narrowing on `==` comparisons

Aperta
#10,708 1 commento 1 reazione 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

feature topic-plugins
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

Feature

I'm proposing a new plugin interface for type narrowing on == comparisons.

Pitch

Take the following code:

from enum import IntEnum

class MyIntEnum(IntEnum):
    A = 1
    B = 2

m: MyIntEnum

if m == 1:
    pass
else:
    reveal_type(m)

This should reveal MyIntEnum.B, but mypy can't know that because it has no idea about how the __eq__ method on MyIntEnum works.
A plugin interface together with a builtin plugin could fix that.

mypy would walk through the MyIntEnum MRO until it encounters a class that defines __eq__ and then look for a plugin able to handle this class.

The plugin matching the class will be called and can return two types. One narrowing for if the condition matches and one for if it doesn't.

This would also be useful for checking match statements (#10191). Currently I have to special case enums there, as match always compares emums with ==, while mypy only narrows types if enums are compared with is.

It would probably also make it possible to get rid of the special casing of a == type(A) and replace it with a plugin.

I would like to first hear some opinions about this before I start implementing it.

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 esaminando le interfacce dei plugin esistenti di mypy e il comportamento attuale del restringimento degli enum per == rispetto a is. Esamina quindi il caso di un'istruzione match a cui si fa riferimento in #10191 e definisci come un plugin restituirebbe i tipi ristretti per i confronti corrispondenti e non corrispondenti.

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

Valutazione

Stack tecnologico
python
Ambito
compilers
Tipo di issue
Funzionalità
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Ferma
Chiarezza
Da chiarire
Idoneità per principianti
20/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.