Try block handling assumes all statements could have succeeded
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 a try block is used to attempt to convert/consolidate the type of a variable, the except block assumes the conversion may or may not have happened. For try blocks with multiple statements, this is the correct behavior for every line but the final one as mypy can't know which of those lines succeeded. However, I would expect mypy to understand that the last/only line can't have executed.
To Reproduce
Minimal example similar to where I encountered the issue:
# file: type_test.py
import sys
from importlib import import_module
from types import ModuleType
def ensure_module(module: str | ModuleType) -> ModuleType:
if isinstance(module, str):
try:
module = import_module(module)
except ImportError:
sys.path.append('/path/to/extra/modules')
# mypy thinks module could be either a string or ModuleType
module = import_module(module)
return module
Expected Behavior
mypy shouldn't have any errors:
$ python -m mypy type_test.py
Success: no issues found in 1 source file
Actual Behavior
mypy finds an error in the except block:
$ python -m mypy type_test.py
type_test.py:14: error: Argument 1 to "import_module" has incompatible type "Union[str, Module]"; expected "str"
Found 1 error in 1 file (checked 1 source file)
Your Environment
- Mypy version used:
mypy 0.961 (compiled: yes) - Mypy command-line flags: N/A
- Mypy configuration options from
mypy.ini(and other config files): N/A - Python version used: 3.10.5
- Operating system and version: Arch Linux (5.18.11-zen1-1-zen)
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 eseguendo con mypy l’esempio minimo in type_test.py e riproduci l’errore nel blocco except. Analizza il restringimento dei tipi di try/except per l’assegnazione finale, quindi verifica che l’esempio non segnali errori mantenendo il comportamento corretto per più istruzioni.
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