Raymond Hettinger wrote: >> I don't use __del__ much. I use it only in leaf classes, where it >> surely can't be part of loops. In those rare cases, it's very useful >> to me. For instance, I have a small classes which wraps an existing >> handle-based C API exported to Python. Something along the lines of: >> >> class Wrapper: >> def __init__(self, *args): >> self.handle = CAPI.init(*args) >> >> def __del__(self, *args): >> CAPI.close(self.handle) >> >> def foo(self): >> CAPI.foo(self.handle) >> >> The real class isn't much longer than this (really). How do you >> propose to write this same code without __del__? >> >> > Use weakref and apply the usual idioms for the callbacks: > > class Wrapper: > def __init__(self, *args): > self.handle = CAPI.init(*args) > self._wr = weakref.ref(self, lambda wr, h=self.handle: > CAPI.close(h)) > > def foo(self): > CAPI.foo(self.handle)
What happens if self.handle changes? Or if it's closed, so that weakref should be destroyed? You will have to bookkeep _wr everywhere across the class code. You're proposing to remove a simple method that is easy to use and explain, but that can cause complex problems in some cases (cycles). The alternative is a complex finalization system, which uses weakrefs, delayed function calls, and must be written smartly to avoid keeping references to "self". I don't see this as a progress. On the other hand, __close__ is easy to understand, maintain, and would solve one problem of __del__. I think what Python 2.x really needs is a better way (library + interpreter support) to debug cycles (both collectable and uncollectable, as the frormer type can be just as bad as the latter time in real-time applications). Removing __del__ just complicates real-world use cases without providing a comprehensive solution to the problem. Giovanni Bajo _______________________________________________ Python-3000 mailing list [email protected] http://mail.python.org/mailman/listinfo/python-3000 Unsubscribe: http://mail.python.org/mailman/options/python-3000/archive%40mail-archive.com
