Next / Previous / Contents / TCC Help System / NM Tech homepage

26.3.12. __exit__: Context manager cleanup

For a general explanation of context managers, see Section 23.9, “The with statement and context managers”. A class that acts a content manager must provide this special method as well as the one described in Section 26.3.11, “__enter__: Context manager initialization”.

When the body of a with statement completes its execution, the .__exit__() method of the related context manager M is called with three arguments. If the block terminated without raising an exception, all three arguments will be None; otherwise see below.

M.__exit__(self, eType, eValue, eTrace)
eType

The type of the exception.

eValue

The exception instance raised.

eTrace

A traceback instance. For more information about stack traces, see the documentation for the traceback module.

Your .__exit__() method's return value determines what happens next if the block raised an exception. If it returns True, Python ignores the exception and proceeds with execution at a point just after the with block. If you don't want your context manager to suppress the exception, don't re-raise it explicitly, just return False and Python will then re-raise the exception.