GC and finalizers [was: No destructor]

Martin von Loewis loewis at informatik.hu-berlin.de
Thu Aug 24 08:44:15 EDT 2000


Paul Duffin <pduffin at hursley.ibm.com> writes:

> Even if A and B both had finalisers then it could be cleaned up, you
> just have to be careful and set out various dos and don'ts for 
> finalisers. 
> 
> Can you give an example of finalisers for A and B which would cause 
> problems ?

Suppose the following scenario:

class Head:
  def __del__(self):
    free_resource(self.next.item)

class Middle:
  pass

class Tail:
  def __del__(self):
    pass

h=Head()
h.next=Middle()
h.next.item=obtain_resource()  # returns int, head object is responsible
                               # for resource
t=Tail()
h.next.val=t
t.next=h
del h
del t

Now, clean-up of head, middle, and tail could occur in arbitrary order.
Clean-up proceeds in the following way:
- __del__ is called
- the instance dictionay is cleared
Clearing the instance dictionary will release further objects, which
thus breaks the cycle.

Assume clean-up starts with the middle object. It invokes __del__
(nothing to do), then clears the instance dictionary. As a result, the
value of middle.item is gone. Cleanup of head would fail, as it would
not find self.next.item; the resource would be lost.

Regards,
Martin




More information about the Python-list mailing list