does python have useless destructors?

Carl Banks imbosol at aerojockey.invalid
Sun Jun 13 12:03:50 CEST 2004


"Martin v. L?wis" wrote:
>> myfile = open("myfilepath", "w")
>> myfile.write(reallybigbuffer)
>> myfile.close()
>> 
>> If the write fails due to a lack of disk space, the exception will
>> prevent the explicit close() from happening. Now, if myfile goes out of
>> scope, I would hope that the file object is destroyed and thus the file
>> is closed, but after reading the python documentation, it seems that
>> the only way to guarantee closure of the file is using the mentioned
>> try/finally construct...
> 
> C-Python 2.3.4 will close the fil if myfile goes out of scope,

Not so fast, my friend.  What if reallybigbuffer is an instance of the
following class, defined in the same function:

    class reallybigbufferclass(object):
        def __str__(self): __builtins__.myfile = myfile; return "sucker!"

Whoops, looks like there's still a reference hanging around.  Python
STILL doesn't guarantee this file will be closed upon exit.  Even more
perniciously:

    class reallybigbufferclass(object):
        def __init__(self): self.self = self
        def __str__(self): self.myfile = myfile; return "sucker!"
        def __del__(self): pass

I think if reallybigbuffer goes out of scope and no one else
references it, then myfile will never be closed, ever.  At least not
until someone gets at it using the gc module.

These are silly examples, of course, but with more intricate stuff (or
with code by other people who are always less disciplined than you)
this can become a real problem.  Face it, people, it's ludicrous to
rely on the garbage collector to finalize stuff for us.


-- 
CARL BANKS                      http://www.aerojockey.com/software
"If you believe in yourself, drink your school, stay on drugs, and
don't do milk, you can get work." 
          -- Parody of Mr. T from a Robert Smigel Cartoon



More information about the Python-list mailing list