Skip to content
CloudOps
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.
Newsletter

Free: the DevOps AI Incident-Triage Cheat Sheet

Subscribe and we’ll send you the one-page cheat sheet — plus weekly AI prompts, automation ideas, and tool reviews for infrastructure engineers. One email a week. No spam, unsubscribe anytime.

  • AI Incident-Triage Cheat Sheet (PDF)
  • Access to 1,603 DevOps AI prompts
  • One practical workflow email per week