Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python context manager exit: returning true can hide a failure

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

A context manager __exit__ method receives exception information when its with body fails and can suppress that exception by returning a true value.

Download Python source kit

Operation contract

The first owned guard records ValueError and declines suppression, so the caller catches the failure. The second guard explicitly suppresses that one type. Other failures still propagate. A real transaction wrapper should normally roll back and let unexpected errors reach the caller; silent suppression can turn a failed write into an apparent success.

Failure and ownership boundary

The example logs only exception type, avoiding payloads in diagnostic output. The method is invoked on normal exit as well, with no active exception. Returning true in every case is dangerous because it would hide programming errors. Python context managers: clean up on success and failure and Python ExitStack pop_all: transfer cleanup without discarding it handle resource lifetime separately from failure policy.

Working program

python
class FailureGuard:
    def __init__(self, suppress=False):
        self.suppress = suppress
        self.seen = []
    def __enter__(self):
        return self
    def __exit__(self, failure_type, failure, traceback):
        self.seen.append(None if failure_type is None else failure_type.__name__)
        return self.suppress and failure_type is ValueError

strict = FailureGuard()
try:
    with strict:
        raise ValueError("invalid receipt")
except ValueError:
    print("strict propagated:", strict.seen)
soft = FailureGuard(suppress=True)
with soft:
    raise ValueError("invalid receipt")
print("soft continued:", soft.seen)

Output

Output
strict propagated: ['ValueError']
soft continued: ['ValueError']

Costs and limits

Exit invokes one callback for this one guard; actual cleanup cost belongs to the resource. Suppression changes control flow, not the work already performed before the exception. State changes require rollback or compensation as a separate operation.

Common Mistakes

  • A true __exit__ return suppresses the exception.
  • Suppressing an exception does not roll back earlier state changes.

Connected lessons

Python context managers: clean up on success and failure, Python exceptions: translate an input error without hiding its cause, Python SQLite savepoints: discard one substep without committing the batch.

python
context-exit-suppression
Storage details