Repaso
EspaƱol
PythonAdvancedPY-13

In a context manager, what happens if __exit__ returns True?

Options

  1. The with block is executed again from the beginning
  2. Any exception raised inside the block is suppressed (Correct option)
  3. The resource stays open until the program ends
  4. __enter__ is called again to restore the resource

Answer

Any exception raised inside the block is suppressed

Why

A context manager (what you use with with) has __enter__, which runs at the start, and __exit__, which runs at the end, even when there is an error.

If an exception happens inside the block, Python passes it to __exit__. If __exit__ returns True, Python considers the error handled and does not raise it.

Returning False or None lets the error continue.

Remember

__exit__ returning True swallows the exception.

Key terms

Practice this question in Repaso