How To Iterate Through Every Class Declaration, Descended From A Particular Base Class?
I was wandering how does elixir\sqlalchemy get to know all the entity classes I've declared in my model, when I call setup_all()? I need that kind of functionality in a little proj
Solution 1:
For class definitions, this is easier (no importing)
def find_subclasses(cls):
results = []
for sc in cls.__subclasses__():
results.append(sc)
return results
I'm not sure if you wanted this, or objects. If you want objects:
import gc
deffind_subclasses(cls):
results = []
for sc in cls.__subclasses__():
for obj in gc.get_objects():
ifisinstance(obj, sc):
results.append(obj)
return results
Solution 2:
Answering the main question, without dealign with SQLALchemy or elixir at all - yes, it is possible in Python.
The garbage colector (gc
) module on the standard library, have a function call that allows one to retrieve all references to a given object, interpreter wide. A class is always referred to in the __mro__
attribute of any inherited classes.
So, the following function could retrieve all classes that inherit from a given class:
import gc
deffind_subclasses(cls):
all_refs = gc.get_referrers(cls)
results = []
for obj in all_refs:
# __mro__ attributes are tuples# and if a tuple is found here, the given class is one of its membersif (isinstance(obj, tuple) and# check if the found tuple is the __mro__ attribute of a classgetattr(obj[0], "__mro__", None) is obj):
results.append(obj[0])
return results
Post a Comment for "How To Iterate Through Every Class Declaration, Descended From A Particular Base Class?"