[Python-3000] PEP: Eliminate del (original) (raw)
Guido van Rossum guido at python.org
Fri May 4 20:09:42 CEST 2007
- Previous message: [Python-3000] PEP: Eliminate __del__
- Next message: [Python-3000] PEP: Eliminate __del__
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On 5/4/07, Steven Bethard <steven.bethard at gmail.com> wrote:
On 5/4/07, Guido van Rossum <guido at python.org> wrote: > On 5/4/07, Raymond Hettinger <python at rcn.com> wrote: > > An encapsulating function should be added to the weakref module > > so that Guido's example could be written as: > > > > class BufferedWriter: > > > > def init(self, raw): > > self.raw = raw > > self.buffer = "" > > weakref.cleanup(self, lambda s: s.raw.write(s.buffer)) > > Or, instead of a new lambda, just use the unbound method: > > weakref.cleanup(self, self.class.flush) > > Important: use the dynamic class (self.class), not the static > class (BufferedWriter). The distinction matters when BufferedWriter is > subclassed and the subclass overrides flush(). > > Hm, a thought just occurred to me. Why not arrange for object.new > to call [the moral equivalent of] weakref.cleanup(self, > self.class.del), and get rid of the direct call to del > from the destructor? (And the special-casing of objects with del > in the GC module, of course.)
That seems like a good idea, though I'm still a little unclear as to how far the AttrMap should be going to look like a real instance. As it stands, you can only access items from the instance dict. That means no methods, class attributes, etc.::
Oh, you mean 'self' as passed to the callback is not the instance? That kills the whole idea (since the typical del calls self.flush() or self.close()).
>>> import weakref >>> def cleanup(obj, callback, reg=[]): ... class AttrMap(object): ... def init(self, map): ... self.map = map ... def getattr(self, key): ... return self.map[key] ... def wrapper(wr, mp=AttrMap(obj.dict), callback=callback): ... reg.remove(wr) ... callback(mp) ... reg.append(weakref.ref(obj, wrapper)) ... >>> class Object(object): ... # note that we do this in init because in new, the ... # object has no references to it yet ... def init(self): ... super(Object, self).init() ... if hasattr(self.class, 'newdel'): ... # note we use .imfunc so that we can later pass ... # any object as the "self" parameter ... cleanup(self, self.class.newdel.imfunc) ... >>> class Foo(Object): ... def flush(self): ... print 'flushing' ... def newdel(self): ... print 'deleting' ... self.flush() ... >>> f = Foo() >>> del f deleting Exception exceptions.KeyError: 'flush' in ignored
If it really has to be done this way, I think the whole PEP is doomed.
-- --Guido van Rossum (home page: http://www.python.org/~guido/)
- Previous message: [Python-3000] PEP: Eliminate __del__
- Next message: [Python-3000] PEP: Eliminate __del__
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]