mypy can not correctly tell when optional type can not be None
Offen
Dieses Issue hat noch niemand übernommen.
bug
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Bug Report
mypy can not correctly tell when optional type can not be None if the variable was previously set or checked in @property.
To Reproduce
class Test(object):
def __init__(self) -> None:
self.test: str | None = None
@property
def is_set(self) -> bool:
return self.test is not None
def failed_check(self) -> None:
if not self.is_set:
return
# self.test can not be None
value = self.test.strip(',')
print(value)
class Test2(object):
def __init__(self) -> None:
self.test: str | None = None
def set_me(self) -> None:
self.test = 'test'
def use_me(self) -> None:
self.set_me()
# self.test can not be None
self.test.strip(',')
Expected Behavior
No issues found.
Actual Behavior
test.py:14: error: Item "None" of "Optional[str]" has no attribute "strip" [union-attr]
test.py:28: error: Item "None" of "Optional[str]" has no attribute "strip" [union-attr]
Found 2 errors in 1 file (checked 1 source file)
Your Environment
- Mypy version used: mypy 0.991 (compiled: yes)
- Mypy command-line flags:
mypy test.py - Mypy configuration options fro m
mypy.ini(and other config files): - Python version used: Python 3.10.8
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
Beginne damit, die Beispiele als test.py zu speichern und mypy test.py mit den angegebenen Python- und mypy-Versionen auszuführen. Verfolge, wie mypy Optional-Werte nach Eigenschaftsprüfungen und Methodenaufrufen eingrenzt; abgeschlossen ist die Aufgabe, wenn beide Beispiele keine Fehler erzeugen und eine Regressionstestabdeckung für das gemeldete Verhalten vorhanden ist.
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