[Python-3000] PEP: Eliminate __del__
jimjjewett at gmail.com
Tue May 1 17:43:33 CEST 2007
On 5/1/07, Raymond Hettinger <python at rcn.com> wrote:
> The alternative is to code the automatic finalization steps using
> weakref callbacks. For those used to using __del__, it takes a little
> while to learn the idiom but essentially the technique is hold a proxy
> or ref with a callback to a boundmethod for finalization:
> self.resource = resource = CreateResource()
> self.callbacks.append(proxy(resource, resource.closedown))
> In this manner, all of the object's resources can be freed automatically
> when the object is collected. Note, that the callbacks only bind
> the resource object and not client object, so the client object
> can already have been collected and the teardown code can be run
> without risk of resurrecting the client (with a possibly invalid state).
That alternative is pretty ugly, and I think we found some cases where
it required major rewriting. (I don't have them handy, but may end up
searching for them again, if need be.)
A smaller change would be to add __close__ (which covers most use
cases), or even to give __del__ the __close__ semantics.
The key distinction is that __close__ says to go ahead and break the
cycle in an arbitrary location, rather than immortalizing it.
More information about the Python-3000