mypy ignores type checking and produces error for union types when using `is` keyword to check the boolean result from `isinstance()`
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
When using the is True or is False keywords in the if statement along with isinstance, mypy does not recognize the type checking and produces an error, and ignores the instance type checking.
To Reproduce
from typing import Union
class A:
prop: str = "Test"
prop2: int = 999
class B:
prop: str = "Test 2"
AB = Union[A, B]
if __name__ == '__main__':
test_var: AB = A()
if isinstance(test_var, A) is True:
print(test_var.prop2)```
Playground: https://mypy-play.net/?mypy=latest&python=3.9&gist=7c4401069c861413b72a395a4ce92757
Expected Behavior
I expected that both expressions below were interpreted the same way by mypy as both are syntactically valid and produce the same result:
Using the is keyword to check the result:
if isinstance(test_var, A) is True:
pass
No is keyword:
if isinstance(test_var, A):
pass
Actual Behavior
main.py:19: error: Item "B" of "Union[A, B]" has no attribute "prop2" [union-attr]
Found 1 error in 1 file (checked 1 source file)
Your Environment
- Mypy version used: 0.991
- Mypy command-line flags:
--follow-imports silent - Mypy configuration options from
mypy.ini(and other config files):-
python_version = 3.9 warn_return_any = True warn_unused_configs = True ignore_missing_imports = True disallow_untyped_defs = True disallow_incomplete_defs = True check_untyped_defs = True disallow_untyped_decorators = True no_implicit_optional = True strict_equality = True warn_redundant_casts = True warn_unused_ignores = True show_error_codes = True
-
- Python version used: 3.9
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 segnalato nel mypy playground collegato con Python 3.9 e mypy 0.991, confrontando isinstance(test_var, A) con isinstance(test_var, A) is True. Traccia il modo in cui mypy restringe i tipi unione per queste condizioni e aggiungi un test di regressione; il lavoro è completato quando entrambe le forme riconoscono test_var come A senza l’errore di attributo dell’unione.
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
- 42/100