Why no open(f, "w").write()?

Delaney, Timothy tdelaney at avaya.com
Wed May 29 20:47:18 EDT 2002


> From: pinard at iro.umontreal.ca [mailto:pinard at iro.umontreal.ca]
> 
> The current (C-)Python implementation is of high quality on 
> that respect,
> and after checking with knowledgeable people, I got that the 
> dependability
> of refcounts could be considered as cast in stone, exactly 
> like if it has
> been documented as such.  If I did not get this confirmation 
> first, I would
> never have started to use things like "open(FILE, 
> 'w').write(CONTENTS)".
> Now, I really see it as part of (unwritten) specifications of 
> (C-)Python,
> and perfectly legitimate.

I can come up with a perfectly good example where

	open(FILE, 'w').write(CONTENTS)

will fail to close the file in CPython.

There are no guarantees that the reference to the object returned is the
*only* reference to that object. Assume the following (perverse)
implementation of open:

__files = []

def open (path, mode):
    f = __open(path, mode)
    __files.append(f)
    return f

or

class file:

    __files = []

    def __init__(self, path, mode):
        __files.append(self)

Whilst I know this is not the implementation, there is nothing that prevents
it from being like this. So you get back an object that has one more
reference count than expected. It never gets collected.

You should never rely on automatic freeing of *any* resources unless it is
guaranteed. Always explicitly free resources when you have finished with
them.

Tim Delaney





More information about the Python-list mailing list