Type-narrowing does not apply across 2 branches having the same condition within the same block

Offen
#7,928 2 Kommentare 2 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
42/100
Issue-Typ
Feature
Klarheit
Größtenteils klar
Aktivitätsstatus
Veraltet
Tech-Stack
python
Bereich
compilers, tooling

Rechercherichtung

Beginnen Sie mit dem Reproducer a.py und führen Sie mypy mit --strict-optional aus, um die aktuelle Diagnose zu bestätigen. Verfolgen Sie die Typverengung für die beiden wiederholten if created:-Blöcke und fügen Sie anschließend eine Abdeckung hinzu, die zeigt, dass die zweite Verwendung von a ohne Fehler akzeptiert wird.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Beschreibung

feature needs discussion priority-2-low topic-type-narrowing
  • Are you reporting a bug, or opening a feature request?
    Feature request

  • Please insert below the code you are checking with mypy,

from typing import Optional

def my_func() -> bool:
  return True

created: bool = my_func()
a: Optional[int] = None
if created:
  a = 1
  z = a + 1 # This is OK

if created:
  x = a + 1 # Unsupported operand types for + ("None" and "int")
  • What is the actual behavior/output?
$ mypy a.py
a.py:13: error: Unsupported operand types for + ("None" and "int")
a.py:13: note: Left operand is of type "Optional[int]"
Found 1 error in 1 file (checked 1 source file)
  • What is the behavior/output you expect?

No errors. Mypy should be able to narrow the type of a to just int in the second if block, because it narrowed it to that type already the first if block and they have the exact same condition.

You can argue that it's easy to workaround it be merging the if blocks, but in real-life code, there could easily be intervening code that is not trivial to move around.

  • What are the versions of mypy and Python you are using?
    mypy 0.750+dev.5b73e2a5e62d3da723ac517fabacaa2a0c8cdf3c
    Python 3.7.4

  • What are the mypy flags you are using? (For example --strict-optional)
    --strict-optional

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.