Context managers and exceptions

with is a protocol of two methods, and the second of them can do something no destructor can: suppress an exception. Hence suppress, a way to swallow an error unnoticed, and the chains through which the real cause of a failure is recovered.

L1 · 9 minL2 · 10 min📱 phoneverified · CPython 3.11, linux x86-64

1Predict

Commit to an output and a reason before you open the answer.

Snippet A
class Sup:
    def __enter__(self): return self
    def __exit__(self, *a): return True

with Sup():
    raise ValueError("so what?")
print("got here")
got here
The exception was raised and went nowhere.
Snippet B
class Bad:
    def __enter__(self): return self
    def __exit__(self, *a): raise RuntimeError("from exit")

try:
    with Bad():
        raise ValueError("original")
except Exception as e:
    print(type(e).__name__, e)
    print("context:", type(e.__context__).__name__)
RuntimeError from exit
context: ValueError
What came out is not the exception that was raised. But the original did not vanish.
Snippet C
def g():
    try:
        raise ValueError("lost")
    finally:
        return "swallowed"

print(g())
swallowed
There was an exception. It is gone, and nobody will ever know.
Snippet D
def f():
    try:
        1 / 0
    except ZeroDivisionError:
        raise ValueError("wrapped")

try:
    f()
except ValueError as e:
    print(type(e.__context__).__name__, e.__cause__)
ZeroDivisionError None
Nobody wrote from for the original error, and yet it was preserved.

2Mechanism

The protocol here is as modest as it gets — two methods — but the second of them is given a power that exists nowhere else in the language.

__enter__ is called on entry; what it returns goes into as.

__exit__(exc_type, exc, tb) is called on exit always — on normal completion, on an exception, on return, on break. If the body completed normally, all three arguments are None.

A true value returned from __exit__ suppresses the exception. Returning None lets it through.

Consequence 1 · suppression is a standard feature, not a side effect

Snippet A. __exit__ returned True, the exception is stopped, and execution continues with the next line after the block. This is not a hack: the language deliberately gives the manager the right to decide the exception's fate, because otherwise contextlib.suppress could not be written.

And right there is a trap. A method that happens to return something true — for instance, one ending in return self.close(), where close returns a number — starts swallowing every exception in the block. No errors, green tests, data quietly lost. Hence the rule: __exit__ either explicitly returns None or returns a boolean deliberately.

Consequence 2 · an exception inside __exit__ replaces the original

Snippet B. If __exit__ itself fails, its exception goes out — the original is displaced. That is logical: the handler broke, and it cannot be trusted.

But the original does not disappear. Python records it in the new exception's __context__ and prints it in the traceback with the line “During handling of the above exception, another exception occurred”. The mechanism is called implicit chaining, and it works whenever an exception is raised while another is being handled.

The practical value is direct: when you see such a double traceback, read the top part — that is where the cause is, and the bottom part is only what broke during clean-up.

Consequence 3 · finally with return destroys the exception

Snippet C is the most dangerous in the lesson. finally runs on leaving the block in every case, including stack unwinding during an exception. And a return inside it completes the function normally, cancelling the unwinding: the exception is not suppressed by a handler — it simply ceases to exist.

break and continue inside finally do the same. There is no warning; the error vanishes without a trace, along with its traceback. Unlike consequence 1, not even a __context__ remains here.

The conclusion has no exceptions: finally is no place for transferring control. Clean-up only.

Consequence 4 · two chains, explicit and implicit

Snippet D. An exception has two fields for linking to a previous one. __context__ is filled automatically when a new exception arises while an old one is being handled — that is exactly what happened here, although nobody wrote from. __cause__ is filled explicitly through raise ... from e and means “here is the real cause”.

The difference is visible in the traceback: the implicit link is printed as “another exception occurred”, the explicit one as “The above exception was the direct cause”. The first reads as “and the clean-up broke too”, the second as “here is why”.

Hence a rule for your own wrappers over other people's errors: always raise MyError(...) from e. It costs two words, and the difference is whether the next person recovers the cause of the failure in a minute or in an hour.

3Limits of the model

Where this stops holding

__exit__ is called, but it is not guaranteed to get the chance. A crash of the process, os._exit, being killed by a signal — all bypass it. The guarantee covers normal stack unwinding, not every way a program can end.

A manager made from a generator is single-use. @contextlib.contextmanager wraps a generator, and a generator is exhausted after the first pass. Entering the same object again gives a RuntimeError; for a reusable one you need a class or a fresh call to the factory.

Exception groups have their own syntax. Since 3.11 ExceptionGroup carries several errors at once, and they are caught with except*, not an ordinary except. An ordinary except ValueError, faced with a group that has a ValueError inside, will not catch it 🔒 — this is what people trip over when moving to TaskGroup.

4Root

Root R4: behaviour is defined by a protocol. with knows nothing about files or locks — it knows two names and calls them. Hence anything can be a manager, including an object that has no resource at all.

The protocol appeared in 2005 (PEP 343) with a very concrete motivation: try/finally code for acquiring and releasing was repeated everywhere, written with mistakes and hard to read. The solution was deliberately made a protocol rather than an operator with fixed semantics — and that is exactly why with is used today for things nobody thought of in 2005: timing, substitution in tests, transactions, limiting the precision of computations, redirecting output.

The right to suppress an exception was added at the same moment and not without argument: it makes possible both suppress and the silent loss of errors. Expressiveness was chosen.

5Analogy

with is RAII with an explicit scope. In C++ a resource is released when the object leaves its scope; in Python, when execution leaves the block. Both constructs exist so that a release cannot be forgotten, and both fire during stack unwinding.

They part ways in two places, and both are telling. First: RAII is tied to a type, while with is tied to the point of use; so in C++ you cannot forget to release but also cannot decide not to, while in Python you can do either. Second: a destructor has no access to the exception in flight and cannot cancel it, while __exit__ receives it whole, with its type and traceback, and decides its fate.

The second difference is the very reason contextlib.suppress exists in Python and has no counterpart in C++.

6Questions a careful reader asks

Questions that come up on their own if you read closely. The answer is under the question.

Why is a bare except: bad, if it catches everything?

Exactly because of that: it also catches what must not be caught.

A bare except: is equivalent to except BaseException:, and three things that must pass straight through inherit from BaseException: KeyboardInterrupt, SystemExit and GeneratorExit.

while True:
    try:
        do_work()
    except:              # swallows Ctrl-C
        continue

This loop cannot be stopped from the keyboard: every keypress is caught and ignored. The same with sys.exit() inside the block — the process will not exit. And a swallowed GeneratorExit breaks the closing of generators and gives RuntimeError: generator ignored GeneratorExit.

The right boundary is except Exception: it catches everything application-level and lets control signals through. And even it is appropriate only at the top level — in a request handler, in a worker's main loop — where the task is “log it and move on to the next item”.

for item in queue:
    try:
        handle(item)
    except Exception:                  # not BaseException
        log.exception("failed on %s", item)   # with a traceback, not str(e)

And separately: log.exception instead of log.error(str(e)). An exception string without a traceback is the most common reason an incident cannot be taken apart: you see what, you do not see where.

Why raise ... from, if the context is preserved anyway?

Because the automatic context says “happened during”, while from says “happened because of”. Those are different statements.

Python stores two different references. __context__ is set by itself when one exception arose inside the handling of another. __cause__ is set only by an explicit from and means a cause-and-effect link.

try:
    try: 1 / 0
    except ZeroDivisionError as e:
        raise ValueError("bad data")
except ValueError as e:
    print(e.__context__, "|", e.__cause__)
# → division by zero | None

In the traceback the difference is visible in words: without from it prints “During handling of the above exception, another exception occurred”, with from — “The above exception was the direct cause”.

And a third form people forget: raise ... from None — it suppresses the chain entirely. It is needed where the inner exception is an implementation detail that there is no point showing to the library's user:

def get_config(d, key):
    try:
        return d[key]
    except KeyError:
        raise ConfigError(f"no key {key}") from None   # the KeyError will not surface

The rule: from e — when you repackage someone else's error into your own and want to keep the trail. from None — when someone else's error was a way of learning a fact, not the problem itself. Nothing — when the exception arose by accident and the chain honestly reflects that.

Why does return in finally swallow an exception — is that not a bug?

Not a bug but a direct consequence of finally having to run on any exit from the block.

If finally contains return, break or continue, they define a new way of leaving the function — and it replaces the one that was in progress. The exception in flight simply stops flying.

def f():
    try:
        raise ValueError("an important error")
    finally:
        return "all good"

print(f())      # → all good      the exception vanished without a trace

No traceback, no log entry, no trace in __context__. From the caller's point of view the function completed successfully.

What this looks like in real code. Not so explicit: usually it is a finally that does clean-up and returns a status just in case, or a loop with a continue in finally for the sake of “skip the broken record”. The second variant is especially treacherous — it swallows KeyboardInterrupt too.

In 3.14 a compiler warning (SyntaxWarning) was added for this construct, but the behaviour was kept — R9: the semantics cannot be changed, existing code may have come to rely on it. So there is a diagnostic, but no protection.

The rule: finally is for clean-up only. Everything that changes the flow of control goes into else or after the block.

with or try/finally — is there a difference besides brevity?

There is, and a significant one: __exit__ sees the exception and can suppress it, while finally cannot.

finally runs “blind”: it does not know whether the block was left normally or with an error, or which one. __exit__ receives three arguments — type, value, traceback — and its return value decides the exception's fate.

class Suppress:
    def __enter__(self): return self
    def __exit__(self, exc_type, exc, tb):
        print("caught:", exc_type)
        return exc_type is ValueError     # True → the exception is suppressed

with Suppress():
    raise ValueError("quietly")
print("got here")
# → caught: <class 'ValueError'>
# → got here

contextlib.suppress rests on this, and so do transactions that roll back on an error and commit on success, telling the cases apart.

The second difference is reuse. try/finally has to be repeated in every place; a manager is written once and gets a name. Plus contextlib.contextmanager lets you describe one with a generator, where yield is the boundary of the block.

Where try/finally is appropriate after all: one-off clean-up for which creating a class is overkill, and cases where entry and exit are not paired — for example, the resource was acquired further up the stack.

The important common point: the power to suppress an exception is something a C++ destructor does not have. There an exception cannot be let out of a destructor at all, and the decision about the error's fate is made outside RAII. Here it is the other way round.

Bottom line. with is a protocol of two methods: __enter__ hands a value to as, and __exit__ is always called and receives the exception in flight whole. Returning a true value from __exit__ suppresses the exception — a standard power on which suppress rests, and at the same time a way to swallow an error unnoticed if the method happens to return something true. An exception raised inside __exit__ replaces the original but does not destroy it: the original is kept in __context__, and in a double traceback you read the top part. A return inside finally, however, destroys the exception without a trace, along with its traceback — which is why finally is a place for clean-up only. And the two chains differ in meaning: __context__ is filled automatically and means “broke during handling”, __cause__ is set by an explicit raise ... from and means “here is the cause” — two words that save an hour of investigation.
From here on — optional
counterfactualC++ RAII, Go defer, JavaA destructor cannot cancel an exception — __exit__ can

C++ RAII is the same task, solved earlier and more strictly. A destructor is called on leaving a scope, including during stack unwinding, and that is more reliable than with: nothing needs to be written at the point of use, release is tied to the type. But a destructor cannot suppress an exception — and if it throws its own during unwinding, it ends the program outright through std::terminate. Compare with snippet B, where Python calmly replaces one exception with another and keeps the original in __context__.

Hence also the absence of finally in C++: it is not needed, because clean-up lives in destructors. Python went the other way — it gave an explicit construct, and got RAII-like behaviour from the reference count (lesson 09), but only as an implementation detail.

Go with its defer is closer to finally: a deferred call on leaving the function, and through recover it too can stop a panic. Java made try-with-resources — a narrow special case of with, working only with AutoCloseable and with no right to suppress.

Four languages, one task, and only two of them allow the cleaner to cancel the crash.

🐛 bugAn __exit__ that returns the wrong thingThe method ends with a call that returns a true value — and the block stops letting errors out

A transaction manager. Written carefully, passed review, and errors stopped reaching the logs.

class Transaction:
    def __enter__(self):
        self.conn = pool.acquire()
        return self.conn

    def __exit__(self, exc_type, exc, tb):
        if exc_type is None:
            self.conn.commit()
        else:
            self.conn.rollback()
        return pool.release(self.conn)     # ← right here

The author wrote return to “return the connection to the pool” — following the meaning of the phrase, not the meaning of the protocol. And pool.release returns, say, the number of free connections. The number is non-zero, so true, so every exception inside the block is suppressed.

with Transaction() as conn:
    process(conn)          # fails
# we end up here as if nothing happened, the rollback is done,
# nothing went upward, the logs are empty

The worst thing about this bug is that the rollback works. The data is consistent, while the calling code considers the operation successful and moves on. The discrepancy will surface much later and somewhere else.

def __exit__(self, exc_type, exc, tb):
    ...
    pool.release(self.conn)
    return None                # or simply return nothing

The rule from consequence 1: nothing is returned from __exit__ unless you are deliberately suppressing. You can check the existing managers in a codebase by grepping for def __exit__ — any return with a non-empty expression deserves a look.

⚡ techniquecontextlib instead of your own classesA generator, suppress and ExitStack cover almost every case without a single class

A class with two dunders gets written out of habit. In most cases a decorator over a generator is enough.

from contextlib import contextmanager

@contextmanager
def timed(label):
    t = time.perf_counter()
    try:
        yield
    finally:
        log.info("%s: %.3f c", label, time.perf_counter() - t)

It reads like an ordinary function: before yield is the entry, after it the exit, and try/finally guarantees clean-up on an exception. Eight lines instead of a class, and all the logic is visible in execution order rather than split across two methods.

suppress is that same consequence 1 ready-made, and it is more honest than an empty except:

from contextlib import suppress

with suppress(FileNotFoundError):
    os.remove(path)

# instead of
try:
    os.remove(path)
except FileNotFoundError:
    pass

ExitStack solves what a class solves awkwardly: a number of resources not known in advance. They are closed in reverse order, as they should be.

with ExitStack() as stack:
    files = [stack.enter_context(open(p)) for p in paths]
    process(files)          # all of them get closed, however many there are

When a class after all: the manager has to be reusable (a generator is single-use, see “Limits of the model”), you need state between entries, or the object exists anyway and it is natural to give it the protocol.

💻 terminalCheck it in the REPLFour snippets plus the order of ExitStack, nested with, and except*

Run the four snippets and check them against your prediction. Then:

from contextlib import ExitStack
with ExitStack() as st:
    st.callback(lambda: print("1"))
    st.callback(lambda: print("2"))
# In what order, and why exactly that way?

with A() as a, B() as b:
    ...
# If B.__enter__ fails — will A.__exit__ be called?
# And if A.__enter__ fails — will B.__enter__ be called?

try:
    raise ExceptionGroup("g", [ValueError("a")])
except ValueError:
    print("caught")
# Will it catch it? And with except* ValueError?

@contextmanager
def cm():
    yield 1
c = cm()
with c: pass
with c: pass
# What happens on the second entry?

The third question matters in practice when moving to TaskGroup: an ordinary except does not catch a group, and code that worked with gather stops handling errors.

sourcecontextlib and decimalHow a manager is made from a generator, and where with is used for something other than resources

Lib/contextlib.py, the _GeneratorContextManager class. Worth reading in full — it shows how a generator turns into a manager: __enter__ does next(gen) and returns the yielded value, and __exit__, on an exception, calls gen.throw(exc), that is, throws the exception into the generator at the point of yield. That is why a try/finally around yield works as expected.

It also shows where suppression comes from: if after throw the generator finished without an exception, it has absorbed it, and __exit__ returns True. Consequence 1 in thirty lines of code.

Lib/decimal.py, localcontext. An example of with with no resource at all: the manager substitutes the global precision settings for the duration of the block and restores the previous ones on exit. The same technique is in every manager that temporarily changes state: unittest.mock.patch, numpy.errstate, torch.no_grad. Understanding that with is just a pair of calls explains all of them at once.

L2What the compiler does with with, and how unwinding worksSETUP_WITH, the order of calls, and zero-cost exceptions in 3.11

From L1 you know the protocol. Here: what it turns into and what it costs.

The compiler unfolds with into a sequence: get the type's __exit__ (the type's, precisely — it is a protocol, lesson 11), call __enter__, run the body, call __exit__ with three arguments. Both methods are fetched before entering the block, so substituting __exit__ on the instance inside the body has no effect.

The answer to the “Check it yourself” question about with A() as a, B() as b follows from here: it is exactly nested blocks, so a failure of B.__enter__ will call A.__exit__, while a failure of A.__enter__ leaves B untouched — it was never reached.

On the cost of exceptions. Before 3.11, entering a try cost an instruction: a handler block was set up on the stack. Since 3.11 (the same work that gave inline caches) there is a move to an exception table: bytecode ranges and their handlers live in a separate structure of the code object, and entering a try costs nothing — only the path where an exception actually occurs pays.

def f():
    try: pass
    except: pass
f.__code__.co_exceptiontable      # b'' if no handler is needed

The practical consequence: the old advice “do not wrap hot code in try” is out of date. Wrapping is free; only raising an exception is expensive — and that is still worth avoiding in a hot loop, in favour of a check.

L3Where this is in the CPython sourcescontextlib.py, bytecodes.c, PEP 343 and PEP 654

Tag v3.11.15.

  • Lib/contextlib.py — the whole module in Python; it reads in twenty minutes and shows better than any explanation that with is just two calls.
  • Python/ceval.c, the BEFORE_WITH and WITH_EXCEPT_START instructions — what exactly the compiler generates.
  • Objects/exceptions.c — the fields __context__, __cause__ and __suppress_context__, and the logic that fills them when an exception is raised.
  • PEP 343 — the introduction of with; the motivation collects all the repeated try/finally blocks it was made for. PEP 654 — exception groups and except*.
connectionsWhere this leadsL11, L09, L14 · the contrast with RAII, defer and try-with-resources
root R4 · Protocols instead of interfaces
← foundation L11 · Protocols — __enter__ and __exit__ are taken from the type, not the instance
← foundation L09 · Reference counting — why with is required, even though the object will be destroyed anyway
↔ contrast RAII in C++: more reliable, but a destructor cannot cancel an exception
↔ contrast defer in Go and try-with-resources in Java — two narrower solutions to the same task
→ next L14 · async/await — the asynchronous variant of the protocol, and why TaskGroup requires except*
not covered here How a generator can take an exception in through throw — that is R5, lesson 13
readingFurther readingcontextlib.py 🟥 · PEP 343 🟧 · PEP 654 🟦

Written by · The Python Canon