Deleting objects with method reference

Peter Otten __peter__ at web.de
Wed Apr 14 05:05:26 EDT 2004


Martin wrote:

> I can't delete this object after I call the Set() function.
> 
> Why is this so special, and are there any way around it besides removing
> the ref ?
> 
> class B:
>    def __del__(self):
>       print "del"
>    def F(self):
>       print "f"
>    def Set(self):
>       self.v = self.F
> 
> 
> o1 = B()
> o1.Set()
> del o1
> 
> 
> o2 = B()
> o2.Set()
> o2.v = None
> del o2
>>>> "del"

self.F consists of a function and an instance reference, so you are
introducing a cycle with o1 referring self.F and self.F referring to o1.
Cycles can only be garbage-collected if the objects involved do not have a
__del__() method. In your example o1 would be collected if you weren't
looking, i. e. B wouldn't attempt to trace the deletion with __del__().
See http://www.python.org/doc/current/lib/module-gc.html, especially the
"garbage" section for details.

You can verify this with a weakref.ref object with an appropriate callback:

import weakref
def ondel(o):
    print "del"

class B:
   def F(self):
      print "f"
   def Set(self):
      self.v = self.F


o1 = B()
o1.Set()
w = weakref.ref(o1, ondel)
del o1

Peter




More information about the Python-list mailing list