Skip to content

Documentation: context manager __exit__ exception behavior wording is incomplete #139320

@vanschelven

Description

@vanschelven

The documentation for [context manager protocol](https://docs.python.org/3/library/stdtypes.html#contextmanager.__exit__) currently says:

"Exceptions that occur during execution of this method will replace any exception that occurred in the body of the with statement."

This phrasing suggests that the original exception is discarded. In practice (since Python 3.0, when implicit exception chaining was introduced), an exception raised inside __exit__ becomes the one that propagates, but the original exception is not lost: it is attached as the new exception’s __context__.

The effect is that tracebacks show:

Traceback (most recent call last):
  ...
During handling of the above exception, another exception occurred:
  ...

So the original error remains visible to users and available in the exception object, rather than being fully replaced.

Suggested improvement

Change the sentence to something like:

"Exceptions that occur during execution of this method replace the exception from the body of the with statement, with the original preserved as context."

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsDocumentation in the Doc dir

    Projects

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions