Optional types not fully narrowed with multiple conditionals

Offen
#16,515 0 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

Bewertung

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

Rechercherichtung

Reproduziere das Beispiel in sandbox.py mit mypy 1.7.0, Python 3.12 und ohne Konfigurationsflags und verfolge dann das Verhalten der Typverengung für die mehreren Bedingungen. Die Arbeit ist abgeschlossen, wenn y als int erkannt wird und die Rückgabe ohne den gemeldeten Fehler wegen eines nicht unterstützten Operanden durchläuft.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Beschreibung

feature topic-type-narrowing

Bug Report

Mypy does not fully narrow optional types when multiple conditionals are involved. I suspect this is because it is not able to make an inference step when performing type narrowing. e.g., below, you have facts ~ (x is None and y is None) and x is None on line 6, which allows you to narrow y: int | None to y: int. y: None can't happen, because y is None -> ~ x is None -> contradiction given the above facts.

To Reproduce

def f(x: int | None, y: int | None) -> int:
    if x is None and y is None:
        return 0
    if x is None:
        # y guaranteed non-null
        reveal_type(y) # int | None, but should be int
        return y + 1

Expected Behavior

mypy should narrow y to int.

Actual Behavior

mypy is not able to narrow y from int | None, and gives a false positive error:

sandbox.py:5: note: Revealed type is "Union[builtins.int, None]"
sandbox.py:6: error: Unsupported operand types for + ("None" and "int")  [operator]
sandbox.py:6: note: Left operand is of type "int | None"

Your Environment

  • Mypy version used: 1.7.0
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.12.0
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
Ø Merge
1 T. 18 Std.
Gemergte PRs (30 T.)
54

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lesen Sie das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreiben Sie ins Issue, dass Sie es übernehmen — das erspart doppelte Arbeit.
  3. Forken Sie das Repository und arbeiten Sie in einem Branch.
  4. Öffnen Sie einen Pull Request, der die Issue-Nummer nennt.

Mehr aus python/mypy

Alle Issues in python/mypy

Ähnliche Issues

Weitere Issues zu Python

Neue Issues direkt in Ihr Postfach

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