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

Advanced Context Managers

python Python 3.1+ Intermediate

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 38
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings W 0 pings T 3 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 2 pings F 0 pings S 1 ping S 0 pings M 0 pings T 0 pings W 0 pings T 4 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 1 ping T 2 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T
No pings yet today
No pings yesterday
Amazonbot 14 Perplexity 11 Google 3 Ahrefs 2 Meta AI 2 ChatGPT 1 Unknown AI 1
crawler 33 crawler_json 1
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