python / python/mypy

Try block handling assumes all statements could have succeeded

Open
#13,123 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the minimal example in type_test.py with mypy and reproduce the error in the except block. Investigate try/except type narrowing for the final assignment, then verify that the example reports no errors while preserving correct behavior for multiple statements.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.