[Python-3000] PEP: Eliminate __del__

Raymond Hettinger python at rcn.com
Fri May 4 17:22:45 CEST 2007

[Michael Bayer]
> why not encapsulate the "proper" weakref-based approach in an easy-to- 
> use method such as "__close__()" ?  that way nobody has to guess how  
> to follow this pattern.

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))
  def write(self, data):
    self.buffer += data
    if len(self.buffer) >= 8192:

  def flush(self):
    self.buffer = ""

I've got a first cut at an encapsulating function but am not happy with it yet.
There is almost certainly a better way.  First draft:

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.append(ref(obj, wrapper))


More information about the Python-3000 mailing list