__Subclasses__ behavior when deleting classes

Edit: Generalized question due to NPE comment.

In an interactive Python 2.7.3 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'>] 

Why is Bar still available through the __subclasses__ function? I expected this to be garbage collection.

And vice versa, if I want it to be garbage collection, how do I do it?

+4
source share
1 answer

Watch this stream . It would seem that what happens is that the class __mro__ attribute stores a reference to itself, creating a reference loop. You can force a full gc run, which will determine the loop and delete the object:

 >>> class Foo(object): pass >>> class Bar(Foo): pass >>> import gc >>> del Bar >>> gc.collect() 3 >>> Foo.__subclasses__() [] 

Alternatively, if you enter other commands for a while, gc will start on its own and build a loop.

Note that you should be a little careful when testing this interactively, because the interactive interpreter stores a reference to the most recent return value in the variable "last value" _ . If you explicitly look at the list of a subclass, and then immediately try to compile, it will not work, because the variable _ will contain a list with a strong reference to the class.

+5
source

All Articles