Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R1732: Consider using 'with' for resource-allocating operations (consider-using-with)

I am running pylint for bug detection in my project and stumble on this warning. How can I fix this warning?

like image 276
Thinh Le Avatar asked May 06 '21 13:05

Thinh Le


1 Answers

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.

like image 169
nobleknight Avatar answered Oct 20 '22 22:10

nobleknight