[Python-Dev] Design question: call __del__ only after successful __init__?

M.-A. Lemburg mal@lemburg.com
Sun, 05 Mar 2000 21:15:47 +0100

Tim Peters wrote:
> [Guido]
> > Would there really be someone out there who uses *intentional*
> > resurrection?  I severely doubt it.  I've never heard of this.
> Why would anyone tell you about something that *works*?!  You rarely hear
> the good stuff, you know.  I gave the typical pattern in the preceding msg.
> To flesh out the motivation more, you have some external resource that's
> very expensive to set up (in KSR's case, it was an IPC connection to a
> remote machine).  Rights to use that resource are handed out in the form of
> an object.  When a client is done using the resource, they *should*
> explicitly use the object's .release() method, but you can't rely on that.
> So the object's __del__ method looks like (for example):
> def __del__(self):
>     # Code not shown to figure out whether to disconnect:  the downside to
>     # disconnecting is that it can cost a bundle to create a new connection.
>     # If the whole app is shutting down, then of course we want to
> disconnect.
>     # Or if a timestamp trace shows that we haven't been making good use of
>     # all the open connections lately, we may want to disconnect too.
>     if decided_to_disconnect:
>         self.external_resource.disconnect()
>     else:
>         # keep the connection alive for reuse
>         global_available_connection_objects.append(self)
> This is simple & effective, and it relies on both intentional resurrection
> and __del__ getting called repeatedly.  I don't claim there's no other way
> to write it, just that there's *been* no problem doing this for a millennium
> <wink>.
> Note that MAL spontaneously sketched similar examples, although I can't say
> whether he's actually done stuff like this.

Not exactly this, but similar things in the weak reference
implementation of mxProxy.

The idea came from a different area: the C implementation
of Python uses free lists a lot and these are basically
implementations of the same idiom: save an allocated
resource for reviving it at some later point.

Marc-Andre Lemburg
Business:                                      http://www.lemburg.com/
Python Pages:                           http://www.lemburg.com/python/