← Home ← Codex ← DEBT
Browse by Category
+ added · updated 7d
← Back to glossary

Advanced Context Managers

Python Python 3.1+ Intermediate
debt(d7/e3/b3/t5)
d7 Detectability Operational debt — how invisible misuse is to your safety net

Closest to 'only careful code review or runtime testing' (d7). pylint/ruff can catch some patterns (e.g. SIM105 for try/except/pass → suppress), but missing context managers around resources like DB connections generally aren't flagged — leaks surface in production or under load testing.

e3 Effort Remediation debt — work required to fix once spotted

Closest to 'simple parameterised fix' (e3). quick_fix is replacing manual resource management with ExitStack or contextlib.suppress — small localized refactors per usage site, not a single-line swap but well-scoped.

b3 Burden Structural debt — long-term weight of choosing wrong

Closest to 'localised tax' (b3). applies_to web/cli; the choice to use (or not use) context managers is generally local to the function handling the resource, not architecturally load-bearing.

t5 Trap Cognitive debt — how counter-intuitive correct behaviour is

Closest to 'notable trap' (t5). The misconception (CMs are only for files) and the @contextmanager 'yield exactly once' rule are documented gotchas most Python devs eventually learn but commonly trip on first.

About DEBT scoring →

Also Known As

contextmanager with statement contextlib __enter__ __exit__

TL;DR

Context managers (with statements) manage resource acquisition and release — contextlib provides tools for creating them without a full class definition.

Explanation

Context managers implement __enter__ and __exit__. contextlib.contextmanager turns a generator function into a context manager — yield once, cleanup after yield runs on exit. contextlib.suppress suppresses specific exceptions. contextlib.ExitStack dynamically composes multiple context managers. contextlib.asynccontextmanager for async with. Use for: database connections, file handles, locks, temporary directories, mocking, and any resource that needs guaranteed cleanup regardless of exceptions.

Common Misconception

Context managers are only for file handling — they are the correct pattern for any resource requiring guaranteed cleanup: DB connections, locks, HTTP sessions, temp files, and test mocking.

Why It Matters

Resources without guaranteed cleanup (DB connections not closed on exception, locks not released on crash) cause resource leaks that accumulate until the service fails.

Common Mistakes

  • Not using a context manager for database connections — connections leak if an exception occurs before close().
  • contextmanager generator that yields more than once — raises RuntimeError; yield exactly once.
  • Not using contextlib.suppress for expected exceptions — try/except/pass where suppress is cleaner.
  • ExitStack not used when the number of context managers is dynamic — manual nesting becomes unmanageable.

Code Examples

✗ Vulnerable
# Resource leak on exception:
def process_file(path):
    f = open(path)
    data = f.read()    # Exception here?
    f.close()          # Never reached — file handle leaked
    return data
✓ Fixed
from contextlib import contextmanager, suppress

# Generator-based context manager:
@contextmanager
def db_transaction(conn):
    try:
        yield conn
        conn.commit()
    except Exception:
        conn.rollback()
        raise
    finally:
        conn.close()  # Always runs

# Usage:
with db_transaction(get_connection()) as conn:
    conn.execute('INSERT INTO orders ...')

# Suppress specific exceptions:
with suppress(FileNotFoundError):
    os.unlink('/tmp/lock_file')  # OK if already gone

Added 15 Mar 2026
Edited 22 Mar 2026
Views 66
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings T 1 ping W 1 ping T 0 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 1 ping T 1 ping F 2 pings S 0 pings S 0 pings M 1 ping T 2 pings W 0 pings T 0 pings F 1 ping S 0 pings S 0 pings M 0 pings T 1 ping W 1 ping T 0 pings F 1 ping S 0 pings S 0 pings M 1 ping T 0 pings W
No pings yet today
PetalBot 1
Amazonbot 17 Perplexity 11 Google 5 Scrapy 5 Ahrefs 4 Meta AI 3 SEMrush 3 Claude 2 Bing 2 PetalBot 2 ChatGPT 1 Unknown AI 1 DuckDuckGo 1
crawler 54 crawler_json 3
DEV INTEL Tools & Severity
🟢 Low ⚙ Fix effort: Medium
⚡ Quick Fix
Use contextlib.ExitStack for managing dynamic numbers of context managers; use contextlib.suppress(ExceptionType) as a clean way to ignore specific exceptions
📦 Applies To
python 3.1 web cli
🔗 Prerequisites
🔍 Detection Hints
Deeply nested with statements; manually managing multiple resources; try/except just to ignore a specific exception when contextlib.suppress would work
Auto-detectable: ✓ Yes pylint ruff
⚠ Related Problems
🤖 AI Agent
Confidence: Medium False Positives: Medium ✓ Auto-fixable Fix: Low Context: Function Tests: Update


✓ schema.org compliant