python-context-managers
verifieda18f165d-9a95-450e-a0f1-595dcea6276a
Write correct context managers in Python — __enter__/__exit__, contextlib, and the resource-safety pitfalls that leak file handles and locks.
Metadata
Skill file
# Python Context Managers
Use when you manage a resource (file, lock, DB connection, socket) that must be
released even when an exception is raised mid-use.
## The `with` protocol
```python
class Managed:
def __enter__(self):
... # acquire resource; return it (or self)
return resource
def __exit__(self, exc_type, exc_val, exc_tb):
... # release resource; return True to suppress exception
```
`__exit__` always runs — the block body may raise, but cleanup runs regardless.
## contextlib shortcuts
- `@contextmanager` + `yield` for read-heavy one-off managers.
- `contextlib.closing(x)` — call `x.close()` on exit.
- `ExitStack` to manage a *dynamic* set of resources (e.g. N files/locks).
## Style
- Prefer `with` over try/finally — it's the same thing, more readable.
- Return the resource from `__enter__` and bind it with `as`.
## Pitfalls
- Forgetting to `return True` (which *suppresses* the exception) — rarely wanted.
- Releasing a resource that was never acquired (guard with a flag).
- A manager that swallows real errors by returning True unconditionally.
- Using `contextmanager` for something with heavy enter/exit logic — a class is clearer.
## Verify
- Raise mid-block and assert cleanup ran (e.g. file closed, lock released).
- Leave the file handle closed; `lsof`/`psutil` shows no leaked descriptors.