python / python/mypy

Ignore incompatible type error when variable is checked in if statement

Offen
#16,645 1 Kommentar 2 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

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

Beschreibung

I'm using mypy for type checking in my Python projects and I've come across a situation where I believe mypy could be improved.

Consider the following code:

def foo1(a: str): ...

def foo2(a: str | None, b: str | None):
    if not a and not b:
        return None
    if not a:
        return foo1(b)
    return None

In this case, mypy raises an error:

Argument 1 to "foo1" has incompatible type "str | None"; expected "str" [arg-type].

However, the function foo1 is only called when b
is not None, so in practice, there is no type error.

The logic of the function ensures that b cannot be None when foo1(b) is called.
This is because in the first if statement, we check if both a and b are None.
If they are not, we proceed to the next if statement where we check if a is None.
If a is None, then b must not be None because of the previous check.
Therefore, foo1(b) is only called when b is not None.

Versions

Python: 3.10.10
MyPy: 1.7.1

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

Führe zunächst mypy für den mitgelieferten Python-Reproducer aus und verfolge, wie sich die beiden if-Anweisungen auf die Typverengung auswirken. Identifiziere die relevanten Tests für die Typprüfung oder den Einstiegspunkt und füge anschließend einen Regressionstest für diesen Kontrollfluss hinzu. Als erledigt gilt die Aufgabe, wenn mypy foo1(b) ohne einen arg-type-Fehler akzeptiert und gleichzeitig die bestehenden Prüfungen beibehält.

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
35/100

Neue Issues direkt in Ihr Postfach

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