[Python-3000] PEP: Eliminate __del__

Guido van Rossum guido at python.org
Fri May 4 06:34:58 CEST 2007


In all the threads about this PEP I still haven't seen a single
example of how to write a finalizer.

Let's take a specific example of a file object (this occurs in io.py
in the p3yk branch). When a write buffer is GC'ed it must be flushed.
The current way of writing this is simple:

class BufferedWriter:

  def __init__(self, raw):
    self.raw = raw
    self.buffer = b""

  def write(self, data):
    self.buffer += data
    if len(self.buffer) >= 8192:
      self.flush()

  def flush(self):
    self.raw.write(self.buffer)
    self.buffer = b""

  def __del__(self):
    self.flush()

How would I write this without using __del__(), e.g. using weak references?

P.S. Don't bother arguing that the caller should use try/finally or
whatever. That's not the point. Assuming we have a class like this
where it has been decided that some method must be called upon
destruction, how do we arrange for that call to happen?

-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-3000 mailing list