False negative: potentially unbound instance attribute doesn't trigger `possibly-undefined` error
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Bug Report
When enabling the possibly-undefined error code, a potentially undefined instance attribute doesn't trigger the error, while a potentially unbound variable does.
To Reproduce
def test_possibly_undefined(flag: bool):
if flag:
a = 1
print(a) # error: Name "a" may be undefined [possibly-undefined]
class Foo:
def test_possibly_undefined(self, flag: bool):
if flag:
self.a = 1
print(self.a) # false negative, should also be a possibly-undefined error
try:
test_possibly_undefined(False)
except Exception as e:
print(f"{type(e).__name__}: {e}") # UnboundLocalError: cannot access local variable 'a' where it is not associated with a value
f = Foo()
try:
f.test_possibly_undefined(False)
except Exception as e:
print(f"{type(e).__name__}: {e}") # AttributeError: 'Foo' object has no attribute 'a'
Also available as mypy Playground, but cannot enable enable_error_code = possibly-undefined there.
Expected Behavior
A possible-undefined error should be reported for line 11 as well, e.g.:
test.py:4: error: Name "a" may be undefined [possibly-undefined]
test.py:11: error: Attribute "a" may be undefined [possibly-undefined]
Found 2 errors in 1 file (checked 1 source file)
Actual Behavior
No error reported for line 11.
test.py:4: error: Name "a" may be undefined [possibly-undefined]
Found 1 error in 1 file (checked 1 source file)
Your Environment
- Mypy version used: 1.11.2
- Mypy command-line flags:
--enable-error-code=possibly-undefined - Mypy configuration options from
mypy.ini(and other config files): None - Python version used: 3.12.6
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, das Beispiel mit mypy 1.11.2 und dem possibly-undefined-Fehlercode zu reproduzieren, und finde dann die Checker-Logik und Regressionstests für möglicherweise nicht definierte lokale Variablen. Vergleiche die Behandlung lokaler Namen mit der von Instanzattributen und füge Abdeckung für das Foo-Beispiel hinzu; fertig ist die Änderung, wenn mypy den erwarteten Fehler Attribute "a" may be undefined meldet.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 45/100