python / python/mypy

Context manager `__exit__` return type `bool | None` is treated as None for reachability analysis

Open
#15,158 2 comments 1 reaction 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

Bug Report

The __exit__ method of a context manager indicates whether an exception should be propagated to the caller by either returning False or None if the exception should be propagated, or by returning True when the exception shouldn't be propagated. Mypy handles these cases w.r.t. reachability analysis as follows:

  • If the return type is None, then the context manager cannot suppress exceptions, hence if the with block unconditionally raises an exception or calls a NoReturn function, statements following after the with block are unreachable.
  • If the return type is bool, the context manager may suppress exceptions. Hence, statements after the with block are considered reachable, independent of what happens in the with block.
  • If the return type is bool | None, mypy treats this currently as the case where the return type is None.

I believe that if the return type is bool | None, mypy should consider this similar to the bool case, as it is possible for the context manager to suppress exceptions and be fine in terms of type checking.

To Reproduce

https://mypy-play.net/?mypy=master&python=3.11&flags=warn-unreachable&gist=579fa731e01cde87fc6ef9062de45d6c

Your Environment

  • Mypy version used: 1.2.0
  • Mypy command-line flags: --warn-unreachable
  • Python version used: 3.11

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 with the mypy-play reproduction using Python 3.11 and --warn-unreachable, then trace how exit return types affect reachability after a with block. Compare the existing handling of None and bool with bool | None; done means the latter is treated as potentially suppressing exceptions and the reproduction no longer reports the following statement as unreachable.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.