Why this ref leak?

Peter Otten __peter__ at web.de
Wed Feb 27 13:51:21 CET 2008


Gerhard Häring wrote:

> import sys
> 
> def foo():
>      class C(object):
>          pass
> 
> foo()
> print ">>", sys.gettotalrefcount()
> foo()
> print ">>", sys.gettotalrefcount()
> foo()
> print ">>", sys.gettotalrefcount()
> 
>  >> 21366
>  >> 21387
>  >> 21408
> [9779 refs]
> 
> Both Python 2.4 and 2.5 don't clean up properly here. Why is this?
> Aren't classes supposed to be garbage-collected?

The reference keeping the classes alive is probably object.__subclasses__():

>>> class A(object): pass
...
>>> sum(1 for c in object.__subclasses__() if c.__name__ == "A")
1
>>> class A(object): pass
...
>>> sum(1 for c in object.__subclasses__() if c.__name__ == "A")
2

Peter



More information about the Python-list mailing list