This suggestion is to ensure the resource is closed or freed when it exits the context. This is the point of using a context manager.
Of course using a context manager breaks in some extent the one-liner style but it brings better/safer code. No chance to forget the close statement. Indeed it is a trade off between readability and good coding practice.
The question is: Is the second line with close statement more readable?
Python documentation states it explicitly:
If you’re not using the with keyword, then you should call f.close()
to close the file and immediately free up any system resources used by
it.
Warning: Calling f.write() without using the with keyword or calling
f.close() might result in the arguments of f.write() not being
completely written to the disk, even if the program exits
successfully.
Anyway the resource should be released when your program exists but it may not be in the state you think it should be.
If the resource is not critical or you think that explicitly write the close statement afterward does not break the one liner style you may ignore this warning.
The risk of keeping files opened are few but you may consider it:
- Dead lock if the resource is locked when opened, it will prevent other process to access it until the lock is released;
- Corruption and unattended behaviour when writing to the resource;
- Reaching the limit of number of files that can be opened by the OS;
The same will happen with database connection:
- Reaching the connection limit due to unclosed connections leading to a service denial.
So, IMHO using the context manager is the good choice to take as it ensures resource to be released as soon as possible, it keeps the code clean and prevent you to forget the required close statement that anyway will break the one-liner style.