python / python/mypy

Inconsistent narrowing of Union and TypeVar with constraints and neglect of @final

Aperta
#10,898 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

I had a short discussion about this with @JelleZijlstra on Gitter.

When narrowing the constrained type variable, Mypy seems to ignore the final decorator. When removing the final decorator, Mypy's output changes neither for the non-generic function f nor the generic function g. Shouldn't Mypy consistently report an error or not in both cases (regardless of marking the classes as final or not)? If I understand correctly, Mypy allows changing the signature of __init__ when subclassing. So the reports are correct for f when using final and correct for g when not using final, aren't they?

from typing import final, Type, TypeVar, Union

@final
class A:
    def __init__(self, a: int) -> None:
        ...

@final
class B:
    def __init__(self, b: str) -> None:
        ...

U = Union[A, B]
T = TypeVar("T", A, B)

def f(x: Type[U]) -> U:
    if issubclass(x, A):
        reveal_type(x)
        # Revealed type is "A"
        return x(a=1)
    return x(b="a")

def g(x: Type[T]) -> T:
    if issubclass(x, A):
        reveal_type(x)
        # Revealed type is "A*"
        # Revealed type is "<subclass of "B" and "A">"
        return x(a=1)
        # Unexpected keyword argument "a" for <subclass of "B" and "A">
    return x(b="b")

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 eseguendo lo snippet Python dell’issue con mypy e confronta i diagnostici e i tipi rivelati con e senza @final. Traccia la gestione dei TypeVars vincolati, del narrowing di Union, dei controlli delle sottoclassi e delle firme dei costruttori; il lavoro è completato quando il comportamento è coerente sia per f sia per g, con classi finali o non finali.

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

Valutazione

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

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.