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
-
Bash Temp File Cleanup with mktemp and trap Prompt
Generate bash scripts that create temp files and directories safely with mktemp and guarantee cleanup on every exit path — normal return, error, and signals — so scripts never leak /tmp garbage or clobber shared filenames.
-
Log Rotation and Cleanup Script Prompt
Generate a safe disk-cleanup and log-rotation script that prunes old logs and artifacts by age and size with dry-run, locking, and guardrails so it never deletes the wrong directory or fills the disk mid-run.
-
Python CSV Data-Quality Validator Prompt
Build a Python CLI that validates and cleans CSV/tabular data against declarative quality rules — types, ranges, required fields, uniqueness, referential checks — and emits a structured report of every violation
-
Python Environment Config Drift Detector Prompt
Build a Python tool that compares configuration or environment-variable sets across environments (dev/staging/prod) and reports missing, extra, and mismatched keys while masking secret values
More Bash & Python Automation prompts & error guides
Browse every Bash & Python Automation prompt and troubleshooting guide in one place.
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.