python / python/mypy

Incorrect narrowing between two different unions

Offen
#20,820 2 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

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

Beschreibung

Bug Report

Narrowing via isinstance and two unions does not seem to do a full crossproduct of possibilities. Spotted when reviewing https://github.com/python/mypy/pull/20743.

To Reproduce

from __future__ import annotations

class A: ...

class B: ...

class C: ...

def f1(x: A | C, t: type[A] | type[B]):
    if isinstance(x, t):
        reveal_type(x)  # N: Revealed type is "__main__.A"
    else:
        reveal_type(x)  # Revealed type is "__main__.A | __main__.C"

Expected Behavior

I would expect the revealed types to be a superset of the results if we did a crossproduct. However, note that <subclass of C and B> is missing. (probably the best way to express this would be to have intersections but... yeah...)

Actual Behavior

Positive branch just has A.

Your Environment

Reproduced in mypy-play

  • Mypy version used: master
  • Mypy command-line flags: N/A
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.12

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 mit dem bereitgestellten Python-Reproducer in mypy-play unter Verwendung von mypy master und Python 3.12 und verfolge anschließend das isinstance-Narrowing-Verhalten in mypy. Als erledigt gilt es, wenn die positiven und negativen reveal_type-Ergebnisse das vollständige in Expected Behavior beschriebene Kreuzprodukt abdecken, einschließlich der fehlenden Möglichkeit einer Unterklasse von C und B.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

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

Neue Issues direkt in Ihr Postfach

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