mypy does not deduce more specific type of generic based on isinstance of 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
The following code:
from dataclasses import dataclass
from typing import Generic, TypeVar, Union
T_co = TypeVar("T_co", covariant=True)
@dataclass(frozen=True)
class Foo(Generic[T_co]):
bar: T_co
def handle_foo_int(foo: Foo[int]) -> None:
pass
def handle_foo(foo: Foo[Union[int, str]]) -> None:
if isinstance(foo.bar, int):
handle_foo_int(foo)
Results in the following error from mypy:
$ mypy test.py
test.py:17: error: Argument 1 to "handle_foo_int" has incompatible type "Foo[Union[int, str]]"; expected "Foo[int]"
If foo.bar is an int, it seems to me that it should imply that foo is a Foo[int]. Is there a way to get mypy to deduce that?
I tested this on 0.761 and 0.770+dev.7af3191246c17a8580acd3b6336f35b02de85e7e.
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 con il riproduttore in test.py ed eseguilo con mypy per confermare l’errore segnalato. Analizza come i controlli isinstance sugli attributi interagiscono con il restringimento dei tipi generici; il lavoro è completato quando l’esempio può passare Foo[Union[int, str]] a handle_foo_int dopo il controllo senza l’errore di tipo incompatibile.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- devtools
- Tipo di issue
- Funzionalità
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100