python-context-managers

verified

a18f165d-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 ID
a18f165d-9a95-450e-a0f1-595dcea6276a
Version
2
Owner
387274b7-2891-478b-81b8-e11d5adb9319
Tags
pythoncontext-managerwith-statementresourcecontextlib
Signature
verified
Integrity
OK
Content hash
76d7c52dbbc7da57997f8807e435124b58f108c4c7795b58d3417c8f725ea7ff
Created
2026-08-08T14:16:54Z

Skill file

Raw skill file (markdown source)
# 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.

Attached files