The fact that the garbage collection will clean up does not mean that you should wait for the garbage collection cycle to clean up.
In particular you should not wait for garbage collection to close file handles, database connections and open network connections.
for example:
In the following code, you assume that the file will be closed on the next garbage collection cycle, if f was the last reference to the file.
>>> f = open("test.txt")
>>> del f
A more explicit way to clean up is to call f.close()
. You can do it even more elegant, that is by using the with
statement, also known as the context manager
:
>>> with open("test.txt") as f:
... pass
... # do something with f
>>> #now the f object still exists, but it is closed
The with
statement allows you to indent your code under the open file. This makes it explicit and easier to see how long a file is kept open. It also always closes a file, even if an exception is raised in the while
block.