when should I explicitly close a file?

Alf P. Steinbach alfps at start.no
Fri Apr 23 13:19:41 CEST 2010

* Adam Tauno Williams:
> On Fri, 2010-04-23 at 16:29 +1200, Lawrence D'Oliveiro wrote:
>> In message <mailman.2119.1271898215.23598.python-list at python.org>, Chris 
>> Rebert wrote:
>>> On Wed, Apr 21, 2010 at 5:53 PM, Lawrence D'Oliveiro wrote:
>>>> In message <4bc9aadb$1 at dnews.tpgi.com.au>, Lie Ryan wrote:
>>>>> Since in python nothing is guaranteed about implicit file close ...
>>>> It is guaranteed that objects with a reference count of zero will be
>>>> disposed.
>>>> In my experiments, this happens immediately.
>>> Experiment with an implementation other than CPython and prepare to be
>>> surprised.
>> Any implementation that doesn’t do reference-counting is brain-damaged.
> Why?

Depends on what the statement was meant to mean.

But for a literal context-free interpretation e.g. the 'sys.getrefcount' 
function is not documented as CPython only and thus an implementation that 
didn't do reference counting would not be a conforming Python implementation.

Whether it uses reference counting to destroy objects at earliest opportunity is 
another matter.

>  There are much better ways to do memory management / garbage
> collection;  especially when dealing with large applications.

Depends on whether you're talking about Python implementations or as a matter of 
general principle, and depends on how you define "better", "large" and so on.

On its own it's a pretty meaningless statement.

But although a small flame war erupted the last time I mentioned this, I think a 
case can be made that Python is not designed for programming-in-the-large. And 
that the current CPython scheme is eminently suitable for small scripts. But it 
has its drawbacks, especially considering the various ways that stack frames can 
be retained, and considering the documentation of 'gc.garbage', ...

   "Objects that have __del__() methods and are part of a reference cycle cause
   the entire reference cycle to be uncollectable, including objects not
   necessarily in the cycle but reachable only from it."

... which means that a programming style assuming current CPython semantics and 
employing RAII can be detrimental in a sufficiently large system.

Cheers & hth.,

- Alf

More information about the Python-list mailing list