Deleting objects with method reference

Peter Otten __peter__ at web.de
Thu Apr 15 08:49:45 EDT 2004


Martin wrote:

> However your example doesn't seem to work.
> 
> import weakref
> import gc
> 
> def ondel(o):
>    print "del"
> 
> class B:
>    def F(self):
>       print "f"
>    def Set(self):
>       self.v = self.F
> 
> o1 = B()
> w1 = weakref.ref(o1, ondel)
> del o1
>>>> del
> 
> o2 = B()
> o2.Set()
> w2 = weakref.ref(o2, ondel)
> del o2
> 
> When I delete o2 I get no output. And gc.garbage is still empty!
> 
> gc.garbage
>>>> []
> 
> I have tried it in both python 2.1 and 2.3.3. Why doesn't it work?

I've cut and pasted the above, put it into ondel.py,
removed 
    >>> del 
added 
    print gc.garbage
as the last line and executed it (on Linux). Here's what I got:

$ python2.1 ondel.py
del
[]
$ python2.2 ondel.py
del
[]
$ python2.3 ondel.py
del
[]
del
$

So at least with python 2.3.3 ondel() is called for both objects. The order
however suggests interference with the shutdown process. Adding 
    gc.collect()
before 
    print gc.garbage
this changes to

$ python2.3 ondel.py
del
del
[]
$ python2.2 ondel.py
del
del
[]
$ python2.1 ondel.py
del
del
[]

which I would have expected in the first place. So why does(n't) it work
that way? I have no idea, but explicitly invoking the garbage collector
does definitely not seem the way to go.

Peter




More information about the Python-list mailing list