Confusion with __del__

Clarence Gardner clarence at netlojix.com
Sun Feb 10 03:37:18 EST 2002


Here is a simple class that uses gdbm. The man page for gdbm says that
it is vital that the file be closed, so I add a __del__ to be sure:

Currently, the initialization of the instance always raises an exception,
so the call to create the instance also deletes it. If I run it interactively,
the write of "in close" happens in an infinite loop, which I don't
understand. 

If I run it under mod_python (which is where it will actually be used but
may be out of scope for this newsgroup), it writes "in close" twice and
then dumps core.  And the cherry on top is that if I remove the write of
"in close", mod_python then goes into an infinite loop also.

It seems to me that what should happen is:
    __init__ raises an exception
    __del__ gets called; it checks whether the "db" attribute exists;
         it doesn't; object is now deleted
Why does it call __del__ (or close) a second (or millionth) time? 

    class ExpirationFile:
        import gdbm
        def __init__(self, name, mode):
            wait = 0.1
            for attempt in range(20):
                try:
                    self.db = gdbm.open(name, mode)
                except:
                    time.sleep(wait)
                else:
                    break
            else:
                open('/tmp/xx','a').write('Unable to open expiration file\n')
                raise KeyError, 'Unable to open expiration file'
        def __setattr__(self, key, value):
            self.db[key] = value
        def __getattr__(self, key):
            return self.db[key]
        def close(self):
            open('/tmp/xx','a').write('in close\n')
            if hasattr(self, 'db'):
                open('/tmp/xx','a').write('attempting to close %s\n' % `self.db`)
                self.db.close()
                del self.db
        __del__ = close



-- 
Clarence Gardner
Software Engineer
NetLojix Communications
clarence at netlojix.com



More information about the Python-list mailing list