Ignore incompatible type error when variable is checked in if statement
Dieses Issue hat noch niemand übernommen.
- 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
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Ö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