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

Python context managers beyond files

Submitted by: @anonymous··
0
Viewed 0 times
context managercontextmanagerwith statementresource cleanupdecorator

Problem

Need to use context managers for database connections, locks, temporary state, and custom resource management.

Solution

Context manager patterns for various resources:

from contextlib import contextmanager, suppress
import time
import os

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

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

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

with cd('/tmp'):
    # Working in /tmp
    pass
# Back to original directory

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

with transaction(db_conn) as conn:
    conn.execute('INSERT ...')
    conn.execute('UPDATE ...')
# Auto-commits or rolls back

# 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

with env_var('DEBUG', 'true'):
    run_tests()

# Suppress specific exceptions
with suppress(FileNotFoundError):
    os.remove('maybe_exists.txt')
# No error if file doesn't exist

# Multiple context managers (Python 3.10+)
with (
    open('input.txt') as fin,
    open('output.txt', 'w') as fout,
    timer('Processing'),
):
    fout.write(fin.read().upper())

Why

Context managers guarantee cleanup even when exceptions occur. They make resource management declarative and prevent leaks.

Context

Python resource management

Revisions (0)

No revisions yet.