Type annotations in class instance attributes on variable definition by execution order vs lexical order
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 20.6k
- Fork
- 3.3k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
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"
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia riproducendo l’esempio in demo.py con mypy e conferma l’errore di attributo duplicato per var3. Poi segui la logica del controllo dei tipi per gli attributi di istanza e l’ordine dei metodi, quindi aggiungi un test di regressione che copra l’annotazione in _reset_state(); il lavoro è completato quando l’esempio viene accettato senza errori e i controlli esistenti rimangono corretti.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- compilers
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100