Solution to finalisation problem [Re: fork()]
Andrew Dalke
dalke at bioreason.com
Thu Jun 17 00:33:18 EDT 1999
Greg Ewing <greg.ewing at compaq.com> 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"
state"""
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):
self.name = name
self.bonds = []
def add_bond(self, bond):
self.bonds.append(bond)
class Bond:
def __init__(self, atoms):
assert len(atoms) == 2
self.atoms = atoms
mol = Molecule()
a1 = Atom("C")
a2 = Atom("O")
mol.atoms.append(a1)
mol.atoms.append(a2)
b = Bond([a1, a2])
a1.add_bond(b)
a2.add_bond(b)
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.
Andrew
dalke at bioreason.com
More information about the Python-list
mailing list