[ZODB-Dev] __del__ with Persistent objects

Jeremy Hylton jeremy at zope.com
Thu Jul 17 14:25:21 EDT 2003


On Thu, 2003-07-17 at 09:05, Stuart Bishop wrote:
> I'm trying to determine if it is possible for a Persistent object
> to sanely clean up external resources it uses. In this case, an
> object that stores a blob of data in file on the filesystem.
> 
> Can the __del__ method be used to remove the external file?
> Basic tests seem to say yes. Can I rely on this behaviour?
> I'm particularly interested with Zope 2.6.2b2

I don't think you can rely on this behavior.  It's probably safe in
versions of ZODB that use ExtensionClass, but the newer ZODB 3.3 and
ZODB 4 will probably behave quite differently.

> __del__ appears to be called when the last reference to the
> Persistent object is removed from the ZODB. However, it is
> possible to undo this transaction.

I don't think removing the object from the database has any direct
effect on __del__.  Rather, it is called when the last reference to the
Python object disappears.  In general, this could happen at any time,
because all the objects that refer to it could be converted to ghosts. 
At that point, the object is still reachable in the database, but Python
has no current references to the object.

If you've got a file descriptor you want to close, you probably want to
do it every time the object becomes a ghost.  When an object becomes a
ghost, it is possible that ZODB will never load the object's state
again.

I think a useful pattern might be to manage the external resource in a
non-persistent object with an __del__.  Use that object only for
finalization.  I think you'd store that object in an _v_ attribute, so
it doesn't get saved in the object pickle.  And you'd have to recreate
the attribute every time __setstate__() was called.

Jeremy





More information about the ZODB-Dev mailing list