ZetCode

Python __exit__ Method

Last modified November 17, 2026 Python 3.15

The with statement calls __exit__ when the block ends, whether normally or because of an exception. The method receives the exception details, performs cleanup, and decides whether to suppress the exception. This article shows those arguments, suppression, reliable cleanup, and a commit-or-rollback transaction manager.

The arguments of __exit__

The hook is called as type(obj).__exit__(obj, exc_type, exc_val, exc_tb). On a normal exit all three exception arguments are None; when the body raises, they hold the exception type, the exception instance, and its traceback.

exit_params.py
class Context:
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("exc_type:", exc_type.__name__ if exc_type else None)
        print("exc_val:", exc_val if exc_val else None)
        print("has traceback:", exc_tb is not None)


print("normal:")
with Context():
    pass

print("with error:")
try:
    with Context():
        raise ValueError("boom")
except ValueError:
    pass

The first block prints None for all three arguments. The second block raises ValueError, so the hook receives that class, the message boom, and a traceback. The surrounding try/except swallows the exception only after the hook has run.

$ python exit_params.py
normal:
exc_type: None
exc_val: None
has traceback: False
with error:
exc_type: ValueError
exc_val: boom
has traceback: True

Suppressing an exception

Returning a true value from __exit__ tells Python the exception was handled, so it is suppressed and execution continues after the with block. Returning None or False lets it propagate.

suppress.py
class Suppress:
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type is ValueError:
            print("suppressing", exc_val)
            return True
        return None


with Suppress():
    raise ValueError("handled")

print("after first")

try:
    with Suppress():
        raise TypeError("not handled")
except TypeError as e:
    print("propagated:", e)

The ValueError is suppressed and the message after the block is printed. The TypeError is not, so it reaches the outer except. Suppressing broadly hides bugs; check the exception type as this example does.

$ python suppress.py
suppressing handled
after first
propagated: not handled

Cleanup still runs on an exception

Because __exit__ is called on every exit path, it is the right place for cleanup. The method below flips a flag and returns False, so the exception is not hidden.

cleanup.py
class Resource:
    def __enter__(self):
        self.closed = False
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("cleanup, closed before:", self.closed)
        self.closed = True
        return False


try:
    with Resource() as r:
        raise RuntimeError("fail")
except RuntimeError as e:
    print("caught:", e)

print("closed after:", r.closed)

The cleanup runs before the exception reaches the caller, and the flag is True afterwards. The object is still accessible after the block through the as target, which is useful for inspecting final state.

$ python cleanup.py
cleanup, closed before: False
caught: fail
closed after: True

Commit or rollback

A transaction manager can use the exception type to choose between committing and rolling back. The cursor returned from __enter__ is used inside the block, and the connection is consulted on the way out.

transaction.py
import sqlite3


class Transaction:
    def __init__(self, conn):
        self.conn = conn

    def __enter__(self):
        return self.conn.cursor()

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type is None:
            self.conn.commit()
            print("committed")
        else:
            self.conn.rollback()
            print("rolled back")
        return False


conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE items (name TEXT)")

with Transaction(conn) as cur:
    cur.execute("INSERT INTO items VALUES ('apple')")

count = conn.execute("SELECT count(*) FROM items").fetchone()[0]
print("count after commit:", count)

try:
    with Transaction(conn) as cur:
        cur.execute("INSERT INTO items VALUES ('pear')")
        raise RuntimeError("abort")
except RuntimeError:
    pass

count = conn.execute("SELECT count(*) FROM items").fetchone()[0]
print("count after rollback:", count)

The first block commits and the row count becomes one. The second block raises, so the hook rolls back and the count stays at one. An in-memory SQLite database keeps the example self-contained and deterministic.

$ python transaction.py
committed
count after commit: 1
rolled back
count after rollback: 1

Best practices

Cleanup is the purpose of this hook, so keep it dependable:

Source

object.__exit__ - Python documentation

contextlib - Python documentation

The with statement - Python documentation

In this article we have implemented the __exit__ method. We have covered its exception arguments, suppression, cleanup on failure, and a transaction manager. For related topics, see Python __enter__ method, Python context managers, and Python with keyword.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.