Looks like a common pattern. Perhaps creating a context manager for this operation might be helpful?