Type annotations in class instance attributes on variable definition by execution order vs lexical order
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- Ø Merge
- 1 T. 18 Std.
- Gemergte PRs (30 T.)
- 54
Beschreibung
Bug Report
Mypy appears to go top down through a class taking the first mention of an instance variable as the definition, and ignores the order of code execution. It also does not accept a type annotation only existing on a later mention of a variable and will only allow type annotations on the first mention of the variable.
To Reproduce
from typing import NamedTuple, Optional
class Foo(NamedTuple):
bar: int = 0
baz: str = ""
class MyClass():
__slots__ = ['var1', 'var2', 'var3']
def __init__(self, foo: Optional[Foo] = None) -> None:
self._reset_state()
if foo:
self.var3 = foo
def _reset_state(self) -> None:
self.var1: int = 0
self.var2: bool = False
self.var3: Foo = Foo()
Expected Behaviour
Mypy recognises the variable is first defined in the _reset_state() method or is only annotated in one place and reports no errors.
Actual Behaviour
$ mypy demo.py
demo.py:18: error: Attribute "var3" already defined on line 13
Found 1 error in 1 file (checked 1 source file)
If the type annotation is removed from line 18 and moved to either line 13, or added to the class body as an attribute annotation mypy reports no errors
Your Environment
- Mypy version used: 0.931
- Mypy command-line flags: N/A
- Mypy configuration options from
mypy.ini(and other config files): default - Python version used: 3.6.9
- Operating system and version: Linux Mint 19.3 Tricia x86_64
I get that this may be the expected/desired behaviour as it may be too complicated otherwise but this was confusing to me. Feel free to close this if you think it is exactly as desired or too hard to "correct"
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 in demo.py mit mypy zu reproduzieren, und bestätige den Fehler wegen des doppelten Attributs für var3. Verfolge dann die Logik der Typprüfung für Instanzattribute und die Reihenfolge der Methoden, und füge einen Regressionstest hinzu, der die Annotation in _reset_state() abdeckt; abgeschlossen ist die Aufgabe, wenn das Beispiel ohne Fehler akzeptiert wird und die bestehenden Prüfungen weiterhin korrekt sind.
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