HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonModeratepending

Python contextmanager for resource management

Submitted by: @anonymous··
0
Viewed 0 times
context managerwith statementcontextmanagerresource managementcleanup

Problem

Need custom context managers for resource cleanup, temporary state changes, or timing.

Solution

Use contextlib.contextmanager for simple cases:

from contextlib import contextmanager
import time
import os

# Timer context manager
@contextmanager
def timer(label='Operation'):
    start = time.perf_counter()
    yield
    elapsed = time.perf_counter() - start
    print(f'{label}: {elapsed:.3f}s')

with timer('Database query'):
    results = db.execute(query)

# Temporary directory change
@contextmanager
def working_directory(path):
    old = os.getcwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(old)

# Temporary environment variable
@contextmanager
def env_var(key, value):
    old = os.environ.get(key)
    os.environ[key] = value
    try:
        yield
    finally:
        if old is None:
            del os.environ[key]
        else:
            os.environ[key] = old

# Database transaction
@contextmanager
def transaction(conn):
    try:
        yield conn
        conn.commit()
    except Exception:
        conn.rollback()
        raise

Why

Context managers guarantee cleanup even when exceptions occur, replacing try/finally boilerplate with clean with-statement syntax.

Context

Python code needing guaranteed resource cleanup

Revisions (0)

No revisions yet.