Context manager `__exit__` return type `bool | None` is treated as None for reachability analysis
Nobody has claimed this yet.
- 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 thewithblock unconditionally raises an exception or calls aNoReturnfunction, statements following after thewithblock are unreachable. - If the return type is
bool, the context manager may suppress exceptions. Hence, statements after thewithblock are considered reachable, independent of what happens in thewithblock. - If the return type is
bool | None, mypy treats this currently as the case where the return type isNone.
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
Your Environment
- Mypy version used: 1.2.0
- Mypy command-line flags:
--warn-unreachable - Python version used: 3.11
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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