It is safe. The __exit__ context manager is called even if you return while inside the context, so the file descriptor is properly closed.
Here is a simple test:
class ContextTest(object): def __enter__(self): print('Enter') def __exit__(self, type, value, traceback): print('Exit') def test(): with ContextTest() as foo: print('Inside') return
When you call test() , you get:
Enter Inside Exit
source share