Having to add type hint 2nd time on AnyStr when assigning as instance attribute
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
I am reporting a potential bug/improvement in mypy.
I assign a class's instance attribute to be an argument from the __init__ signature.
I noticed that when the argument is type hinted as a AnyStr, mypy raises an error unless the instance attribute receives a second type hint.
from typing import AnyStr, Generic
class A(Generic[AnyStr]):
def __init__(self, arg: AnyStr):
# Case A... error: Need type annotation for 'attr'
self.attr = arg
reveal_type(arg)
# note: Revealed type is 'builtins.str*'
# note: Revealed type is 'builtins.bytes*'
reveal_type(self.attr)
# note: Revealed type is 'builtins.str'
# note: Revealed type is 'Any'
# Observation: 'builtins.bytes*' doesn't seem to propagate
class B(Generic[AnyStr]):
def __init__(self, arg: AnyStr):
# Case B... Success
self.attr = arg # type: AnyStr
The desirable behavior is not to have to supply a second type hint.
What's going on here? Is there some way I can not supply a second type hint?
I am invoking mypy from the command line with no flags. Here are my versions:
python==3.6.5
mypy==0.770
Aside
I am coming here from Stack Overflow, where a community member thought it was a bug: Python mypy why does class instance attribute require type hint if expression already has type hint
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 il problema dallo snippet Python incluso con mypy 0.770, confrontando Case A e Case B e i relativi tipi rivelati. Traccia l’inferenza degli attributi di istanza per Generic[AnyStr] e determina se la variabile di tipo dovrebbe propagarsi senza l’annotazione inline. Il lavoro è completato quando Case A non richiede più un secondo suggerimento di tipo ed esiste una copertura di regressione per il comportamento dimostrato.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- devtools
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100