Why this ref leak?

Duncan Booth duncan.booth at invalid.invalid
Wed Feb 27 09:25:15 EST 2008


Peter Otten <__peter__ at web.de> wrote:

> Peter Otten wrote:
> 
>>> 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
> 
> Oops, wrong guess:
> 
>>>> import gc
>>>> gc.collect()
> 6
>>>> sum(1 for c in object.__subclasses__() if c.__name__ == "A")
> 1
> 
The list of subclasses is stored using weak references: that's why you have 
to call a method to create a real list. What actually stops the class just 
vapourising is its __mro__ attribute which creates a cycle, but the garbage 
collector clears that up as you saw.



More information about the Python-list mailing list