Search code examples
pythoniogarbage-collectionfile-descriptor

Does deleting a dictionary close the file descriptors inside the dict?


Clarified

There are two questions indeed. Updated to make this clearer.

I have:

t = {
    'fd': open("filename", 'r')
}

I understand that del t['fd'] removes the key and closes the file. Is that correct?

Does del t call del on contained objects (fd in this case)?


Solution

  • The two parts of your question have completely different answers.

    • Deleting a variable to close file is not reliable; sometimes it works, sometimes it doesn't, or it works but in a surprising way. Occasionally it may lose data. It will definitely fail to report file errors in a useful way.

      The correct ways to close a file are (a) using a with statement, or (b) using the .close() method.

    • Deleting an object indeed deletes all contained objects, with a couple of caveats:

      • if (some of) those objects are also in another variable, they will continue to exist until that other variable is also deleted;

      • if those objects refer to each other, they may continue to exist for some time afterwards and get deleted later; and

      • for immutable objects (strings, integers), Python may decide to keep them around as an optimisation, but this mostly won't be visible to us and will in any case differ between versions.