Solution to finalisation problem [Re: fork()]

Andrew Dalke dalke at
Thu Jun 17 06:33:18 CEST 1999

Greg Ewing <greg.ewing at> said:
> I think what we need at this point is some concrete examples.
> What sorts of things do people actually *do* with __del__
> methods at the moment?

I use them for a few things.  One is to free memory allocated
from a C library, or to remove a temporary file.  This is
effectively your statement:

> As far as I can see, the only thing you really need a
> finalizer for is freeing an external resource.

Most of the uses of __del__ in the std. Python lib. is of this form.

I use __del__ to implement the "resource acquisition is initialization"
idea, as in:

class PreserveMod:
    """Internal class which returns the molecule to its original "mod"
    def __init__(self, mol):
        self.mol = mol
        self.modify = mol.mod
    def __del__(self):
        self.mol.mod = self.modify

Looking at the std. lib., audiodev also uses this style.

Finally, I use __del__ to free cycles which might otherwise arise, as
in this (untested) example:

class Molecule:
  def __init__(self):
    self.atoms = []
    self.bonds = []
  def __del__(self):
    for atom in self.atoms:
      del atom.bonds

class Atom:
  def __init__(self, name): = name
    self.bonds = []
  def add_bond(self, bond):

class Bond:
  def __init__(self, atoms):
    assert len(atoms) == 2
    self.atoms = atoms

mol = Molecule()
a1 = Atom("C")
a2 = Atom("O")
b = Bond([a1, a2])

This has cycles between the atoms and the bonds, but as neither of
them point back to the molecule, I can use the deletion of the
molecule (ref count goes to 0) to trigger a cleanup of the cycles.

						dalke at

More information about the Python-list mailing list