python classes defined dynamically with `type` disappear -
i'm using python's type
dynamically declare classes. like:
class parentclass(object): pass class_name in ['a', 'b', 'c', 'd', 'e']: type(class_name, (parentclass,), {}) print('subclasses of parentclass:', parentclass.__subclasses__())
usually, print line prints 1, 2, 3, 4, , 5 subclasses.
but sometimes, prints 1, 2, 3, 1, 2 subclasses: classes d
, e
. , parentclass.__subclasses__()
anywhere else array [d, e]
.
and weirdest part changing other, unrelated code in other places in project affects it.
is possible that, because i'm not assigning classes name, they're being garbage collected? , that's why parentclass.__subclasses__()
can't find class objects anymore?
is possible that, because i'm not assigning classes name, they're being garbage collected? , that's why
parentclass.__subclasses__()
can't find class objects anymore?
yes, it. see the documentation __subclasses__
method:
each new-style class keeps list of weak references immediate subclasses. method returns list of references still alive.
Comments
Post a Comment