Cannot annotate child of a `Generic[AnyStr]` with an `Optional[AnyStr]` 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
Consider the following code:
from typing import AnyStr, Generic, Optional
class Base(Generic[AnyStr]):
def __init__(self, data: AnyStr) -> None:
self.data: AnyStr = data
class Child(Base):
def __init__(self, data: AnyStr) -> None:
super().__init__(data)
self.buffer: Optional[AnyStr] = None
def act(self, s: AnyStr) -> None:
self.buffer = s
Running mypy on this code produces the following errors:
anystr01.py:13: error: Incompatible types in assignment (expression has type
"str", variable has type "Optional[AnyStr]")
self.buffer = s
^
anystr01.py:13: error: Incompatible types in assignment (expression has type
"bytes", variable has type "Optional[AnyStr]")
self.buffer = s
^
Found 2 errors in 1 file (checked 1 source file)
If I try to address the problem by changing the child class declaration to class Child(Base[AnyStr]):, mypy instead emits the following:
anystr01.py:9: error: Argument 1 to "__init__" of "Base" has incompatible type
"str"; expected "AnyStr"
super().__init__(data)
^
anystr01.py:9: error: Argument 1 to "__init__" of "Base" has incompatible type
"bytes"; expected "AnyStr"
super().__init__(data)
^
Found 2 errors in 1 file (checked 1 source file)
Is this a bug, or am I simply doing something wrong?
Your Environment
- Mypy version used: both 0.961 and commit 132b8e527730b654a3f3d04684bebc9daff6cabd
- Mypy command-line flags:
--pretty - Mypy configuration options from
mypy.ini(and other config files): none - Python version used: 3.9.13
- Operating system and version: macOS 11.6.6
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
Usa lo snippet Python fornito come caso di riproduzione ed esegui mypy con i flag indicati. Traccia l’inferenza dei generics e il controllo delle assegnazioni per Child, Base[AnyStr] e Optional[AnyStr]; il lavoro è completato quando il comportamento è corretto o chiaramente documentato, con copertura di regressione per il caso.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- compilers, 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