Python resource management with context managers

by wshobson · MIT license · ★ 39,857 on GitHub · updated Sep 21

Python resource management cover

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)
Claude Codenpx skills add wshobson/agents --skill python-resource-management -g -a claude-code
Claude Code (manual)mkdir -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-management
Windows (PowerShell)New-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" -Force
Claude.ai / desktopDownload the ZIP and upload it under Settings → Capabilities → Skills.
Codex, Cursor, other agentsPoint them at SKILL.md. The other files are plain text.

Connects with Agent Alley MCP · agentalley.io/mcp

Files included

  • SKILL.md6.8 KB
  • references/1 file · 4.6 KB
Read the files here
wshobson/4236bb92 files
SKILL.md
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

  1. Always use context managers - For any resource that needs cleanup
  2. Clean up unconditionally - __exit__ runs even on exception
  3. Don't suppress unexpectedly - Return False unless suppression is intentional
  4. Use @contextmanager - For simple resource patterns
  5. Implement both protocols - Support with and manual management
  6. Use ExitStack - For dynamic numbers of resources
  7. Accumulate efficiently - List + join, not string concatenation
  8. Track metrics - Time-to-first-byte matters for streaming
  9. Document behavior - Especially exception suppression
  10. Test cleanup paths - Verify resources are released on errors
1---
2name: python-resource-management
3description: 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 
8Manage 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 
23The `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 
35Return `True` from `__exit__` to suppress exceptions, `False` to propagate them.
36 
37## Quick Start
38 
39```python
40from contextlib import contextmanager
41 
42@contextmanager
43def managed_resource():
44 resource = acquire_resource()
45 try:
46 yield resource
47 finally:
48 resource.cleanup()
49 
50with managed_resource() as r:
51 r.do_work()
52```
53 
54## Fundamental Patterns
55 
56### Pattern 1: Class-Based Context Manager
57 
58Implement the context manager protocol for complex resources.
59 
60```python
61class 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)
93with DatabaseConnection(dsn) as db:
94 result = db.execute(query)
95 
96# Manual management when needed
97db = DatabaseConnection(dsn)
98db.connect()
99try:
100 result = db.execute(query)
101finally:
102 db.close()
103```
104 
105### Pattern 2: Async Context Manager
106 
107For async resources, implement the async protocol.
108 
109```python
110class 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
144async 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 
150Simplify context managers with the decorator for straightforward cases.
151 
152```python
153from contextlib import contextmanager, asynccontextmanager
154import time
155import structlog
156 
157logger = structlog.get_logger()
158 
159@contextmanager
160def 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
170with timed_block("data_processing"):
171 process_large_dataset()
172 
173@asynccontextmanager
174async 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
185async 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 
192Always clean up resources in `__exit__`, regardless of exceptions.
193 
194```python
195class 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 
230Detailed 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 
2341. **Always use context managers** - For any resource that needs cleanup
2352. **Clean up unconditionally** - `__exit__` runs even on exception
2363. **Don't suppress unexpectedly** - Return `False` unless suppression is intentional
2374. **Use @contextmanager** - For simple resource patterns
2385. **Implement both protocols** - Support `with` and manual management
2396. **Use ExitStack** - For dynamic numbers of resources
2407. **Accumulate efficiently** - List + join, not string concatenation
2418. **Track metrics** - Time-to-first-byte matters for streaming
2429. **Document behavior** - Especially exception suppression
24310. **Test cleanup paths** - Verify resources are released on errors
244 
View all files on GitHub →

Details

Updated
Sep 21, 2026
License
MIT
Stars on the repo
★ 39,857
Checked
Source
wshobson/agents ↗
Creator
wshobson · 179 listings
View creator

Similar skills

See all →
SkillExtract text, tables, metadataXberg Document Extractionxberg-io/xberg · by xberg-ioExtract text, tables, metadata, and images from 107 document formats (PDF, Office, images, HTML, email, archives, academic) using Xberg. Use when writing code that calls Xberg APIs in Python, Node.js/TypeScript, Rust, or CLI. Covers installation, extraction (sync/async), configuration (OCR, chunking, output format), batch processing, error handling, and plugins.★ 9.4k GitHub starsSkillMove code from one implementation to another functionCode migrationkucherenko/jscpd · by kucherenkoMove code from one implementation to another function by function, tests first and code second, and check two implementations of one app for parity, with jscpd --compare as the progress measure and a coverage map binding each function to its tests. Use when porting a library or app to another language or framework (Java to Kotlin, JavaScript to Rust, a Python library to TypeScript, an iOS app to Android), when asked what is left to port, or when comparing the Android and iOS versions of an app.★ 6.3k GitHub starsSkillManages Ahrefs API usage in Python using ahrefs-pythonOpenClaudia/openclaudia-skills · by OpenClaudiaManages Ahrefs API usage in Python using `ahrefs-python` library. Use when working with SEO / marketing related tasks or with data including backlinks, keywords, domain ratings, organic traffic, site audits, rank tracking, and brand monitoring. Covers `ahrefs-python` usage including AhrefsClient / AsyncAhrefsClient, typed request/response models, error handling, and all API sections.★ 705 GitHub starsMCPDocx LLM translatoradeudealfluence/adeu · by dealfluenceDocx ↔ LLM translator. Projects .docx office files to Markdown for editing. Projects edits back to OOXML as tracked changes (redlines). Python and Node.js implementations.★ 165 GitHub starsSkillCreate an Amazon-compliant white-background main imageAmazon White-Background Main Image · 亚马逊白底主图xianyu110/ecommerce-image-skills · by xianyu110Create an Amazon-compliant white-background main image (pure #FFFFFF background, product fills ≥85% of the frame, no text, props or watermark) from a product photo with GPT Image 2.5, then verify it with a Python check script. Use for Amazon/Walmart/eBay main images, 白底图, 白底主图, hero image, listing main photo.★ 92 GitHub starsMCPOfficial monorepo of SDKs, CLISendmux sdkSendmux/sendmux-sdk · by SendmuxOfficial monorepo of SDKs, CLI, and MCP servers for Sendmux email APIs across TypeScript, Python, Go, PHP, Rust, and Ruby.★ 65 GitHub stars

More from wshobson

SkillMaster C/.NET backend development patterns for buildingwshobson/agents · by wshobsonMaster C#/.NET backend development patterns for building robust APIs, MCP servers, and enterprise applications. Covers async/await, dependency injection, Entity Framework Core, Dapper, configuration, caching, and testing with xUnit. Use when developing .NET backends, reviewing C# code, or designing API architectures.★ 39.9k GitHub starsSkillImplement WCAG 2.2 compliant interfaces with mobileAccessibility compliancewshobson/agents · by wshobsonImplement WCAG 2.2 compliant interfaces with mobile accessibility, inclusive design patterns, and assistive technology support. Use when auditing accessibility, implementing ARIA patterns, building for screen readers, or ensuring inclusive user experiences.★ 39.9k GitHub starsSkillMaster Material Design 3 and Jetpack Compose patternsAndroid Mobile Designwshobson/agents · by wshobsonMaster Material Design 3 and Jetpack Compose patterns for building native Android apps. Use when designing Android interfaces, implementing Compose UI, or following Google's Material Design guidelines.★ 39.9k GitHub starsSkillMigrate from AngularJS to Angular using hybrid modeAngular migrationwshobson/agents · by wshobsonMigrate from AngularJS to Angular using hybrid mode, incremental component rewriting, and dependency injection updates. Use when upgrading AngularJS applications, planning framework migrations, or modernizing legacy Angular code.★ 39.9k GitHub starsSkillUnderstand anti-reversing, obfuscationAnti reversing techniqueswshobson/agents · by wshobsonUnderstand anti-reversing, obfuscation, and protection techniques encountered during software analysis. Use this skill when analyzing malware evasion techniques, when implementing anti-debugging protections for CTF challenges, when reverse engineering packed binaries, or when building security research tools that need to detect virtualized environments.★ 39.9k GitHub starsSkillBuild production Apache Airflow DAGs with best practicesApache Airflow DAG Patternswshobson/agents · by wshobsonBuild production Apache Airflow DAGs with best practices for operators, sensors, testing, and deployment. Use when creating data pipelines, orchestrating workflows, or scheduling batch jobs.★ 39.9k GitHub stars