python / python/mypy

False positive unreachable statement after exception raised within context block

Open
#8,766 5 comments 6 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

import contextlib
from typing import Iterator

@contextlib.contextmanager
def context_func() -> Iterator[None]:
    try:
        yield
    except Exception:
        pass

def foo() -> None:
    with context_func():
        raise Exception

    print("xxx")  # mypy: Statement is unreachable

Since context managers can silence exceptions, I don't think mypy should consider statements after the context to be unreachable due to exceptions which might be raised within the context.

Flags needed: --warn-unreachable.


Python 3.6, mypy 0.770, also master (at 2a3de7b7941f24b6bc53fe0cf8a2b7f8f7fd4e15)

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 provided example with Python and mypy's --warn-unreachable flag, comparing the warning after the context block with the expected behavior. Trace mypy's analysis of exceptions raised inside a context manager and verify that a context manager which catches the exception does not make the following statement unreachable.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.