Implement a context manager with contextlib

Use contextlib to implement a context manager instead of a class.