Python resource management with context managers

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.
--- name: python-resource-management description: 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. --- # 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
Overview
Manage resources deterministically using context managers. Resources like database connections, file handles, and network sockets should be released reliably, even when exceptions occur.
Manual install (npx, ZIP)
npx skills add wshobson/agents --skill python-resource-management -g -a claude-codemkdir -p ~/.claude/skills && curl -sL https://codeload.github.com/wshobson/agents/tar.gz/4236bb91f839 \
| tar -xz -C ~/.claude/skills --strip-components=4 agents-4236bb91f839/plugins/python-development/skills/python-resource-managementNew-Item -ItemType Directory -Force "$HOME\.claude\skills" | Out-Null; Invoke-WebRequest "https://m.agentalley.io/zip/3d5644420d6a71c2bca5/python-resource-management.zip" -OutFile "$env:TEMP\python-resource-management.zip"; Expand-Archive "$env:TEMP\python-resource-management.zip" -DestinationPath "$HOME\.claude\skills" -ForceConnects with Agent Alley MCP · agentalley.io/mcp
Files included
SKILL.md6.8 KBreferences/1 file · 4.6 KB
Read the files here
Show the full text244 lines
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
from contextlib import contextmanager
@contextmanager
def managed_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.
class DatabaseConnection:
"""Database connection with automatic cleanup."""
def __init__(self, dsn: str) -> None:
self._dsn = dsn
self._conn: Connection | None = None
def connect(self) -> None:
"""Establish database connection."""
self._conn = psycopg.connect(self._dsn)
def close(self) -> None:
"""Close connection if open."""
if self._conn is not None:
self._conn.close()
self._conn = None
def __enter__(self) -> "DatabaseConnection":
"""Enter context: connect and return self."""
self.connect()
return self
def __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.
class AsyncDatabasePool:
"""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 = None
async def __aenter__(self) -> "AsyncDatabasePool":
"""Create connection pool."""
self._pool = await asyncpg.create_pool(
self._dsn,
min_size=self._min_size,
max_size=self._max_size,
)
return self
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
"""Close all connections in pool."""
if self._pool is not None:
await self._pool.close()
async def execute(self, query: str, *args) -> list[dict]:
"""Execute query using pooled connection."""
async with self._pool.acquire() as conn:
return await conn.fetch(query, *args)
# Usage
async with 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.
from contextlib import contextmanager, asynccontextmanager
import time
import structlog
logger = structlog.get_logger()
@contextmanager
def timed_block(name: str):
"""Time a block of code."""
start = time.perf_counter()
try:
yield
finally:
elapsed = time.perf_counter() - start
logger.info(f"{name} completed", duration_seconds=round(elapsed, 3))
# Usage
with timed_block("data_processing"):
process_large_dataset()
@asynccontextmanager
async def database_transaction(conn: AsyncConnection):
"""Manage database transaction."""
await conn.execute("BEGIN")
try:
yield conn
await conn.execute("COMMIT")
except Exception:
await conn.execute("ROLLBACK")
raise
# Usage
async with 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.
class FileProcessor:
"""Process file with guaranteed cleanup."""
def __init__(self, path: str) -> None:
self._path = path
self._file: IO | None = None
self._temp_files: list[Path] = []
def __enter__(self) -> "FileProcessor":
self._file = open(self._path, "r")
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
"""Clean up all resources unconditionally."""
# Close main file
if self._file is not None:
self._file.close()
# Clean up any temporary files
for temp_file in self._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
Falseunless suppression is intentional - Use @contextmanager - For simple resource patterns
- Implement both protocols - Support
withand 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
| 1 | |
| 2 | name python-resource-management |
| 3 | description 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. |
| 4 | |
| 5 | |
| 6 | # Python Resource Management |
| 7 | |
| 8 | Manage resources deterministically using context managers. Resources like database connections, file handles, and network sockets should be released reliably, even when exceptions occur. |
| 9 | |
| 10 | ## When to Use This Skill |
| 11 | |
| 12 | Managing database connections and connection pools |
| 13 | Working with file handles and I/O |
| 14 | Implementing custom context managers |
| 15 | Building streaming responses with state |
| 16 | Handling nested resource cleanup |
| 17 | Creating async context managers |
| 18 | |
| 19 | ## Core Concepts |
| 20 | |
| 21 | ### 1. Context Managers |
| 22 | |
| 23 | The `with` statement ensures resources are released automatically, even on exceptions. |
| 24 | |
| 25 | ### 2. Protocol Methods |
| 26 | |
| 27 | `__enter__`/`__exit__` for sync, `__aenter__`/`__aexit__` for async resource management. |
| 28 | |
| 29 | ### 3. Unconditional Cleanup |
| 30 | |
| 31 | `__exit__` always runs, regardless of whether an exception occurred. |
| 32 | |
| 33 | ### 4. Exception Handling |
| 34 | |
| 35 | Return `True` from `__exit__` to suppress exceptions, `False` to propagate them. |
| 36 | |
| 37 | ## Quick Start |
| 38 | |
| 39 | |
| 40 | from contextlib import contextmanager |
| 41 | |
| 42 | @contextmanager |
| 43 | def managed_resource(): |
| 44 | resource = acquire_resource() |
| 45 | try: |
| 46 | yield resource |
| 47 | finally: |
| 48 | resource.cleanup() |
| 49 | |
| 50 | with managed_resource() as r: |
| 51 | r.do_work() |
| 52 | |
| 53 | |
| 54 | ## Fundamental Patterns |
| 55 | |
| 56 | ### Pattern 1: Class-Based Context Manager |
| 57 | |
| 58 | Implement the context manager protocol for complex resources. |
| 59 | |
| 60 | |
| 61 | class DatabaseConnection: |
| 62 | """Database connection with automatic cleanup.""" |
| 63 | |
| 64 | def __init__(self, dsn: str) -> None: |
| 65 | self._dsn = dsn |
| 66 | self._conn: Connection | None = None |
| 67 | |
| 68 | def connect(self) -> None: |
| 69 | """Establish database connection.""" |
| 70 | self._conn = psycopg.connect(self._dsn) |
| 71 | |
| 72 | def close(self) -> None: |
| 73 | """Close connection if open.""" |
| 74 | if self._conn is not None: |
| 75 | self._conn.close() |
| 76 | self._conn = None |
| 77 | |
| 78 | def __enter__(self) -> "DatabaseConnection": |
| 79 | """Enter context: connect and return self.""" |
| 80 | self.connect() |
| 81 | return self |
| 82 | |
| 83 | def __exit__( |
| 84 | self, |
| 85 | exc_type: type[BaseException] | None, |
| 86 | exc_val: BaseException | None, |
| 87 | exc_tb: TracebackType | None, |
| 88 | ) -> None: |
| 89 | """Exit context: always close connection.""" |
| 90 | self.close() |
| 91 | |
| 92 | # Usage with context manager (preferred) |
| 93 | with DatabaseConnection(dsn) as db: |
| 94 | result = db.execute(query) |
| 95 | |
| 96 | # Manual management when needed |
| 97 | db = DatabaseConnection(dsn) |
| 98 | db.connect() |
| 99 | try: |
| 100 | result = db.execute(query) |
| 101 | finally: |
| 102 | db.close() |
| 103 | |
| 104 | |
| 105 | ### Pattern 2: Async Context Manager |
| 106 | |
| 107 | For async resources, implement the async protocol. |
| 108 | |
| 109 | |
| 110 | class AsyncDatabasePool: |
| 111 | """Async database connection pool.""" |
| 112 | |
| 113 | def __init__(self, dsn: str, min_size: int = 1, max_size: int = 10) -> None: |
| 114 | self._dsn = dsn |
| 115 | self._min_size = min_size |
| 116 | self._max_size = max_size |
| 117 | self._pool: asyncpg.Pool | None = None |
| 118 | |
| 119 | async def __aenter__(self) -> "AsyncDatabasePool": |
| 120 | """Create connection pool.""" |
| 121 | self._pool = await asyncpg.create_pool( |
| 122 | self._dsn, |
| 123 | min_size=self._min_size, |
| 124 | max_size=self._max_size, |
| 125 | ) |
| 126 | return self |
| 127 | |
| 128 | async def __aexit__( |
| 129 | self, |
| 130 | exc_type: type[BaseException] | None, |
| 131 | exc_val: BaseException | None, |
| 132 | exc_tb: TracebackType | None, |
| 133 | ) -> None: |
| 134 | """Close all connections in pool.""" |
| 135 | if self._pool is not None: |
| 136 | await self._pool.close() |
| 137 | |
| 138 | async def execute(self, query: str, *args) -> list[dict]: |
| 139 | """Execute query using pooled connection.""" |
| 140 | async with self._pool.acquire() as conn: |
| 141 | return await conn.fetch(query, *args) |
| 142 | |
| 143 | # Usage |
| 144 | async with AsyncDatabasePool(dsn) as pool: |
| 145 | users = await pool.execute("SELECT * FROM users WHERE active = $1", True) |
| 146 | |
| 147 | |
| 148 | ### Pattern 3: Using @contextmanager Decorator |
| 149 | |
| 150 | Simplify context managers with the decorator for straightforward cases. |
| 151 | |
| 152 | |
| 153 | from contextlib import contextmanager, asynccontextmanager |
| 154 | import time |
| 155 | import structlog |
| 156 | |
| 157 | logger = structlog.get_logger() |
| 158 | |
| 159 | @contextmanager |
| 160 | def timed_block(name: str): |
| 161 | """Time a block of code.""" |
| 162 | start = time.perf_counter() |
| 163 | try: |
| 164 | yield |
| 165 | finally: |
| 166 | elapsed = time.perf_counter() - start |
| 167 | logger.info(f"{name} completed", duration_seconds=round(elapsed, 3)) |
| 168 | |
| 169 | # Usage |
| 170 | with timed_block("data_processing"): |
| 171 | process_large_dataset() |
| 172 | |
| 173 | @asynccontextmanager |
| 174 | async def database_transaction(conn: AsyncConnection): |
| 175 | """Manage database transaction.""" |
| 176 | await conn.execute("BEGIN") |
| 177 | try: |
| 178 | yield conn |
| 179 | await conn.execute("COMMIT") |
| 180 | except Exception: |
| 181 | await conn.execute("ROLLBACK") |
| 182 | raise |
| 183 | |
| 184 | # Usage |
| 185 | async with database_transaction(conn) as tx: |
| 186 | await tx.execute("INSERT INTO users ...") |
| 187 | await tx.execute("INSERT INTO audit_log ...") |
| 188 | |
| 189 | |
| 190 | ### Pattern 4: Unconditional Resource Release |
| 191 | |
| 192 | Always clean up resources in `__exit__`, regardless of exceptions. |
| 193 | |
| 194 | |
| 195 | class FileProcessor: |
| 196 | """Process file with guaranteed cleanup.""" |
| 197 | |
| 198 | def __init__(self, path: str) -> None: |
| 199 | self._path = path |
| 200 | self._file: IO | None = None |
| 201 | self._temp_files: list[Path] = [] |
| 202 | |
| 203 | def __enter__(self) -> "FileProcessor": |
| 204 | self._file = open(self._path, "r") |
| 205 | return self |
| 206 | |
| 207 | def __exit__( |
| 208 | self, |
| 209 | exc_type: type[BaseException] | None, |
| 210 | exc_val: BaseException | None, |
| 211 | exc_tb: TracebackType | None, |
| 212 | ) -> None: |
| 213 | """Clean up all resources unconditionally.""" |
| 214 | # Close main file |
| 215 | if self._file is not None: |
| 216 | self._file.close() |
| 217 | |
| 218 | # Clean up any temporary files |
| 219 | for temp_file in self._temp_files: |
| 220 | try: |
| 221 | temp_file.unlink() |
| 222 | except OSError: |
| 223 | pass # Best effort cleanup |
| 224 | |
| 225 | # Return None/False to propagate any exception |
| 226 | |
| 227 | |
| 228 | ## Detailed worked examples and patterns |
| 229 | |
| 230 | Detailed sections (starting with `## Advanced Patterns`) live in `references/details.md`. Read that file when the navigation summary above is insufficient. |
| 231 | |
| 232 | ## Best Practices Summary |
| 233 | |
| 234 | **Always use context managers** - For any resource that needs cleanup |
| 235 | **Clean up unconditionally** - `__exit__` runs even on exception |
| 236 | **Don't suppress unexpectedly** - Return `False` unless suppression is intentional |
| 237 | **Use @contextmanager** - For simple resource patterns |
| 238 | **Implement both protocols** - Support `with` and manual management |
| 239 | **Use ExitStack** - For dynamic numbers of resources |
| 240 | **Accumulate efficiently** - List + join, not string concatenation |
| 241 | **Track metrics** - Time-to-first-byte matters for streaming |
| 242 | **Document behavior** - Especially exception suppression |
| 243 | **Test cleanup paths** - Verify resources are released on errors |
| 244 |
Details
- Updated
- Sep 21, 2026
- License
- MIT
- Stars on the repo
- ★ 39,857
- Checked
- Source
- wshobson/agents ↗
- Creator
- wshobson · 179 listings
Similar skills
See all →
SkillExtract text, tables, metadataXberg Document Extraction
SkillMove code from one implementation to another functionCode migration
SkillManages Ahrefs API usage in Python using ahrefs-python
MCPDocx LLM translatoradeu
SkillCreate an Amazon-compliant white-background main imageAmazon White-Background Main Image · 亚马逊白底主图
MCPOfficial monorepo of SDKs, CLISendmux sdkMore from wshobson
SkillMaster C/.NET backend development patterns for building
SkillImplement WCAG 2.2 compliant interfaces with mobileAccessibility compliance
SkillMaster Material Design 3 and Jetpack Compose patternsAndroid Mobile Design
SkillMigrate from AngularJS to Angular using hybrid modeAngular migration
SkillUnderstand anti-reversing, obfuscationAnti reversing techniques
SkillBuild production Apache Airflow DAGs with best practicesApache Airflow DAG Patterns