Does a File Object Automatically Close when its Reference Count Hits Zero?

The answer is in the link you provided.

Garbage collector will close file when it destroys file object, but:

  • you don’t really have control over when it happens.

    While CPython uses reference counting to deterministically release resources
    (so you can predict when object will be destroyed) other versions don’t have to.
    For example both Jython or IronPython use JVM and .NET garbage collector which
    release (and finalize) objects only when there is need to recover memory
    and might not do that for some object until the end of the program.
    And even for CPython GC algorithm may change in the future as reference counting
    isn’t very efficient.

  • if exception is thrown when closing file on file object destruction,
    you can’t really do anything about it because you won’t know.

Leave a Comment