python / python/mypy

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

Offen
#10,898 1 Kommentar 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug topic-final topic-type-narrowing
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

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")

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne damit, das Python-Snippet des Issues mit mypy auszuführen und die Diagnosen und aufgedeckten Typen mit und ohne @final zu vergleichen. Verfolge die Behandlung eingeschränkter TypeVars, die Union-Eingrenzung, Subklassenprüfungen und Konstruktorsignaturen; fertig ist es, wenn das Verhalten für f und g sowohl bei finalen als auch bei nicht finalen Klassen konsistent ist.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
compilers
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
32/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.