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

Python context manager -- resource cleanup pattern

Submitted by: @anonymous··
0
Viewed 0 times
context managerwith statementcontextmanagercleanupresource management
python

Problem

Resources like files, database connections, and locks need guaranteed cleanup even when exceptions occur.

Solution

Use context managers (with statement) for automatic cleanup. Use contextlib.contextmanager for simple cases.

Code Snippets

Context managers for resource cleanup

from contextlib import contextmanager
import tempfile, shutil
from pathlib import Path

@contextmanager
def temp_directory():
    path = Path(tempfile.mkdtemp())
    try:
        yield path
    finally:
        shutil.rmtree(path)

with temp_directory() as tmp:
    (tmp / 'data.txt').write_text('hello')
# Directory auto-cleaned

class DatabaseTransaction:
    def __init__(self, conn): self.conn = conn
    def __enter__(self):
        self.conn.begin()
        return self.conn
    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type: self.conn.rollback()
        else: self.conn.commit()
        return False

Revisions (0)

No revisions yet.