Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 project of mine, but I have no clue. I've tried to steptrace through elixir's setup_all(), and I found that it keeps a collection of all entity classes in a "global" list (or was it dict?), but I can't catch the moment when the list is filled. Any ideas?

like image 732
AlexVhr Avatar asked Dec 09 '22 03:12

AlexVhr


1 Answers

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

def find_subclasses(cls):
    results = []
    for sc in cls.__subclasses__():
        for obj in gc.get_objects():
            if isinstance(obj, sc):
               results.append(obj)
    return results
like image 191
elijaheac Avatar answered Apr 27 '23 00:04

elijaheac