Edit: Generalised the question due to NPE’s comment.
In a Python 2.7.3 interactive session:
>>> class Foo(object):
... pass
...
>>> type("Bar", (Foo,), {})
<class '__main__.Bar'>
>>> Foo.__subclasses__()
[<class '__main__.Bar'>]
>>>
Also:
>>> class Foo(object):
... pass
...
>>> class Bar(Foo):
... pass
...
>>> Foo.__subclasses__()
[<class '__main__.Bar'>]
>>> del Bar
>>> Foo.__subclasses__()
[<class '__main__.Bar'>]
How come Bar is still available via the __subclasses__ function? I would have expected it to be garbage collected.
Conversely, if I want it to be garbage collected, how do I do it?
See this thread. It would seem that what happens is the class’s
__mro__attribute stores a reference to itself, creating a reference cycle. You can force a full gc run which will detect the cycle and delete the object:Alternatively, if you enter other commands for a while, the gc will run on its own and collect the cycle.
Note that you have to be a bit careful when testing this interactively, because the interactive interpreter stores a reference to the most recently returned value in the “last value” variable
_. If you explicitly look at the subclass list and then immediately try to collect, it won’t work, because the_variable will hold a list with a strong reference to the class.