is open(...).read() a resource leak?

Benjamin Rutt rutt at
Wed Nov 2 21:14:41 CET 2005

"Fredrik Lundh" <fredrik at> writes:

> Benjamin Rutt wrote:
>> If I did the following in an infinite loop, would the host system/user
>> account soon run out of file descriptors?  (I'm thinking no, since I'd
>> imagine that a file object has a __del__-like method that will call
>> close() automatically since it goes out of scope):
>>    open('/home/rutt/.bashrc,'r').read()
> under CPython, this is not a problem (the reference counting system will
> make sure that file handles are reclaimed as fast as new ones are opened).

It would be reclaimed immediately, correct?  (As opposed to waiting
for the next file-open call or some later time).  In my understanding
of CPython gc and reference counting, only the cyclical objects will
be lazily/periodically reclaimed in a scheduled fashion, while all
non-cyclical objects are reclaimed immediately when their last
incoming reference decrements the count to 0.

> under an arbitrary Python implementation, it may be a problem,
> especially if the implementation doesn't trigger a collection if it
> runs out of handles (that can be seen as a bug, though...).

OK, makes sense, thank you.
Benjamin Rutt

More information about the Python-list mailing list