Skip to content
🎉 Launch sale:50% off everything over $22 — automatically applied at checkout· ends Aug 2Shop the sale →
DevOps AI ToolKit
Newsletter
All prompts
AI for Bash & Python Automation Difficulty: Beginner ClaudeChatGPT

Python Context Manager Resource Cleanup Prompt

Wrap acquisition and guaranteed release of a resource (lock, temp dir, DB connection, mounted path) in a custom context manager so cleanup runs even on exceptions

Target user
Python developers replacing fragile try/finally blocks with reusable, composable context managers
Difficulty
Beginner
Tools
Claude, ChatGPT

The prompt

You are a senior Python engineer who specializes in deterministic resource management with context managers.

I will provide:
- The resource I need to acquire and release (e.g. a file lock, temp directory, network mount, started subprocess)
- The exact cleanup that must always run, and whether it can itself fail
- Whether I prefer the `@contextmanager` generator style or a full `__enter__`/`__exit__` class

Your job:

1. **Choose the form** — recommend `@contextlib.contextmanager` for simple cases or a class with `__enter__`/`__exit__` when state or reentrancy matters, and justify the pick.
2. **Acquire and yield** — implement setup before `yield`, returning the resource handle to the `with` block.
3. **Guarantee teardown** — put cleanup in the `finally` (generator) or `__exit__` (class) so it runs on success, exception, and early return.
4. **Handle the exception path** — explain `__exit__(exc_type, exc, tb)` return value semantics (return `True` to suppress, falsy to propagate) and when suppression is dangerous.
5. **Make cleanup itself safe** — guard the teardown so a failure there does not mask the original exception, and log secondary errors.
6. **Compose** — show using `contextlib.ExitStack` to manage several of these resources together with correct reverse-order cleanup.

Output as: one Python module with the context manager, a short `with` usage example, and an `ExitStack` example.

State explicitly when returning `True` from `__exit__` would wrongly swallow a real error.

Run this prompt with AI

Test it, get an AI-improved version, or compare models — live in the Prompt Workspace. No copy-paste.

Related prompts

More Bash & Python Automation prompts & error guides

Browse every Bash & Python Automation prompt and troubleshooting guide in one place.

Free download · 368-page PDF

Reading prompts? Get all 500 in one free PDF

500 battle-tested, copy-paste AI prompts engineered by a senior systems engineer — every one with fill-in placeholders and safety/back-out notes. Drop your email and it's yours.

  • 500 prompts: Linux · Kubernetes · Terraform · OpenStack · GitLab · Docker · Monitoring · Incident Response
  • Instant PDF download — yours free, forever
  • Plus one practical AI-workflow email a week (no spam)

Single opt-in · unsubscribe anytime · no spam.