I am running pylint for bug detection in my project and stumble on this warning. How can I fix this warning?
Asked
Active
Viewed 2.0k times
1 Answers
18
suppose you are opening a file:
file_handle = open("some_file.txt", "r")
...
...
file_handle.close()
You need to close that file manually after required task is done. If it's not closed, then resource (memory/buffer in this case) is wasted.
If you use with
in above example:
with open("some_file.txt", "r") as file_handle:
...
...
there is no need to close that file. Resource de-allocation automatically happens when you use with
.

nobleknight
- 755
- 6
- 15
-
IIRC, using `something = open("a").readlines()` should de-allocate the resource imediatelly, since it is no longer referenced? But pylint still has an issue with this – Mahrkeenerh Mar 11 '22 at 18:49
-
1@Mahrkeenerh No, that will _not_ immediately de-allocate the resource. Even if a resource is no longer referenced, it may not be garbage-collected for some time, if ever. You should never wait until garbage collection to clean up resources. That's why you never override destructors in Python. – Ian Goldby Jun 24 '22 at 11:43