3

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.