On a line such as
r = open(path, encoding="utf-8").read()
Pylint 2.14.5 provides the following advise:
submodules-dedup.py:71:32: R1732: Consider using 'with' for resource-allocating operations (consider-using-with)
If I understand correctly, the suggestion is to change it to
with open(path, encoding="utf-8") as f:
r = f.read()
But is this really better in any way?
Personally I don't find it any more readable, and as for other concerns, wouldn't the file be closed at the same time thanks to how reference counting works anyhow?
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:
The same will happen with database connection:
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.