python-resource-management

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.

By wshobson · 9,713 installs

npx skills add wshobson/agents --skill python-resource-management

Source repository · Upstream listing

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 Fundamental Patterns Pattern 1: Class Based Context Manager Implement the context manager protocol for complex resources. Pattern 2: Async Context Manager For async resources, implement the async protocol. Pattern 3: Using @contextmanager Decorator Simplify context managers with the decorator for straightforward cases. Pattern 4: Unconditional Resource Release Always clean up resources in exit , regardless of exceptions. 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