Install the skill above, then run this in your AI tool:
/python-resource-management <your description>
About
Manage resources deterministically using context managers. Resources like database connections, file handles, and network sockets should be released reliably, even when exceptions occur.
Source
What gets added to your project
Preview every file this package writes on install before you run the command above.
Summary
Python resource management with context managers, cleanup patterns, and streaming. Use when managing connections, file handles, implementing cleanup logic, or building streaming responses with accumulated state.
Skill instructions
Python Resource Management
Manage resources deterministically using context managers. Resources like database connections, file handles, and network sockets should be released reliably, even when exceptions occur.
When to Use This Skill
Managing database connections and connection pools
Working with file handles and I/O
Implementing custom context managers
Building streaming responses with state
Handling nested resource cleanup
Creating async context managers
Core Concepts
1. Context Managers
The with statement ensures resources are released automatically, even on exceptions.
2. Protocol Methods
__enter__/__exit__ for sync, __aenter__/__aexit__ for async resource management.
3. Unconditional Cleanup
__exit__ always runs, regardless of whether an exception occurred.
4. Exception Handling
Return True from __exit__ to suppress exceptions, False to propagate them.
Quick Start
python
from contextlib import contextmanager
@contextmanagerdefmanaged_resource():
resource = acquire_resource()
try:
yield resource
finally:
resource.cleanup()
with managed_resource() as r:
r.do_work()
Fundamental Patterns
Pattern 1: Class-Based Context Manager
Implement the context manager protocol for complex resources.
python
classDatabaseConnection:
"""Database connection with automatic cleanup."""def__init__(self, dsn: str) -> None:
self._dsn = dsn
self._conn: Connection | None = Nonedefconnect(self) -> None:
"""Establish database connection."""self._conn = psycopg.connect(self._dsn)
defclose(self) -> None:
"""Close connection if open."""ifself._conn isnotNone:
self._conn.close()
self._conn = Nonedef__enter__(self) -> "DatabaseConnection":
"""Enter context: connect and return self."""self.connect()
returnselfdef__exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
"""Exit context: always close connection."""self.close()
# Usage with context manager (preferred)with DatabaseConnection(dsn) as db:
result = db.execute(query)
# Manual management when needed
db = DatabaseConnection(dsn)
db.connect()
try:
result = db.execute(query)
finally:
db.close()
Pattern 2: Async Context Manager
For async resources, implement the async protocol.
python
classAsyncDatabasePool:
"""Async database connection pool."""def__init__(self, dsn: str, min_size: int = 1, max_size: int = 10) -> None:
self._dsn = dsn
self._min_size = min_size
self._max_size = max_size
self._pool: asyncpg.Pool | None = Noneasyncdef__aenter__(self) -> "AsyncDatabasePool":
"""Create connection pool."""self._pool = await asyncpg.create_pool(
self._dsn,
min_size=self._min_size,
max_size=self._max_size,
)
returnselfasyncdef__aexit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
"""Close all connections in pool."""ifself._pool isnotNone:
awaitself._pool.close()
asyncdefexecute(self, query: str, *args) -> list[dict]:
"""Execute query using pooled connection."""asyncwithself._pool.acquire() as conn:
returnawait conn.fetch(query, *args)
# Usageasyncwith AsyncDatabasePool(dsn) as pool:
users = await pool.execute("SELECT * FROM users WHERE active = $1", True)
Pattern 3: Using @contextmanager Decorator
Simplify context managers with the decorator for straightforward cases.
python
from contextlib import contextmanager, asynccontextmanager
import time
import structlog
logger = structlog.get_logger()
@contextmanagerdeftimed_block(name: str):
"""Time a block of code."""
start = time.perf_counter()
try:
yieldfinally:
elapsed = time.perf_counter() - start
logger.info(f"{name} completed", duration_seconds=round(elapsed, 3))
# Usagewith timed_block("data_processing"):
process_large_dataset()
@asynccontextmanagerasyncdefdatabase_transaction(conn: AsyncConnection):
"""Manage database transaction."""await conn.execute("BEGIN")
try:
yield conn
await conn.execute("COMMIT")
except Exception:
await conn.execute("ROLLBACK")
raise# Usageasyncwith database_transaction(conn) as tx:
await tx.execute("INSERT INTO users ...")
await tx.execute("INSERT INTO audit_log ...")
Pattern 4: Unconditional Resource Release
Always clean up resources in __exit__, regardless of exceptions.
python
classFileProcessor:
"""Process file with guaranteed cleanup."""def__init__(self, path: str) -> None:
self._path = path
self._file: IO | None = Noneself._temp_files: list[Path] = []
def__enter__(self) -> "FileProcessor":
self._file = open(self._path, "r")
returnselfdef__exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
"""Clean up all resources unconditionally."""# Close main fileifself._file isnotNone:
self._file.close()
# Clean up any temporary filesfor temp_file inself._temp_files:
try:
temp_file.unlink()
except OSError:
pass# Best effort cleanup# Return None/False to propagate any exception
Detailed worked examples and patterns
Detailed sections (starting with ## Advanced Patterns) live in references/details.md. Read that file when the navigation summary above is insufficient.
Best Practices Summary
Always use context managers - For any resource that needs cleanup
Clean up unconditionally - __exit__ runs even on exception
Don't suppress unexpectedly - Return False unless suppression is intentional
Use @contextmanager - For simple resource patterns
Implement both protocols - Support with and manual management
Use ExitStack - For dynamic numbers of resources
Accumulate efficiently - List + join, not string concatenation
Track metrics - Time-to-first-byte matters for streaming
Document behavior - Especially exception suppression
Test cleanup paths - Verify resources are released on errors
Add this badge to a GitHub README so readers can open the package page and install the same version.
[](https://www.aipm-registry.com/skills/wshobson/python-resource-management/1.0.0?utm_source=github&utm_medium=readme&utm_campaign=package_badge)
This imported publisher has not claimed its AIPM account. A connected account confirms account control, but it does not guarantee that a package is safe.
AI assistant context
What this skill is for
@wshobson/python-resource-management@1.0.0 is an AIPM skill package for All tools. Use it when a project needs the reusable AI behavior described as: Python resource management with context managers, cleanup patterns, and streaming. Use when managing connections, file handles, implementing cleanup logic, or building streaming responses with accumulated state.
Run aipm add @wshobson/python-resource-management@1.0.0 in a project that has AIPM initialized.
Supported tools
@wshobson/python-resource-management@1.0.0 supports All tools.
Before installing
AIPM skills can add files to your project. Review the package name, target, description, license, and publisher before installing. Use a clean branch when trying a new skill.