Skip to content

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

Open
@VincentVanlaer

Description

@VincentVanlaer

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-reachabilityDetecting unreachable code

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions