Maybe use this https://docs.python.org/2/library/contextlib.html#contextlib.contextmanager?