In a context manager, what happens if __exit__ returns True?
Options
- The
withblock is executed again from the beginning - Any exception raised inside the block is suppressed (Correct option)
- The resource stays open until the program ends
__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.