Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python classes defined dynamically with `type` disappear

Tags:

python

I'm using python's type to dynamically declare some classes. Something like:

class ParentClass(object):
    pass

for class_name in ['A', 'B', 'C', 'D', 'E']:
    type(class_name, (ParentClass,), {})
    print('subclasses of ParentClass:', ParentClass.__subclasses__())

Usually, the print line prints 1, then 2, 3, 4, and finally all 5 subclasses.

But sometimes, it prints 1, then 2, then 3, then only 1, then 2 subclasses: just the classes D and E. And ParentClass.__subclasses__() anywhere else is just the array [D, E].

And the weirdest part is that changing other, completely unrelated code in other places in the project affects it.

Is it possible that, because I'm not assigning the classes to any name, they're being garbage collected? And that's why ParentClass.__subclasses__() can't find the class objects anymore?

like image 487
Brendan W Avatar asked Mar 11 '26 04:03

Brendan W


1 Answers

Is it possible that, because I'm not assigning the classes to any name, they're being garbage collected? And that's why ParentClass.__subclasses__() can't find the class objects anymore?

Yes, that is exactly it. See the documentation for the __subclasses__ method:

Each new-style class keeps a list of weak references to its immediate subclasses. This method returns a list of all those references still alive.

like image 117
BrenBarn Avatar answered Mar 13 '26 18:03

BrenBarn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!