Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Iterate over all classes

How can I iterate over a list of all classes loaded in memory? I'm thinking of doing it for a backup, looking for all classes inheriting from db.Model (Google App Engine).

Thanks, Neal Walters

like image 542
NealWalters Avatar asked Apr 30 '26 05:04

NealWalters


2 Answers

In "normal" Python, you can reach all objects via the gc.getobjects() function of the gc standard library module; it's then very easy to loop on them, checking which one are classes (rather than instances or anything else -- I do believe you mean instances of classes, but you can very easily get the classes themselves too if that's really what you want), etc.

Unfortunately, the gc module in App Engine does NOT implement getobjects -- which makes it extremely difficult to reach ALL classes. For example, a class created by calling:

def makeaclass():
  class sic(object): pass
  return sic

and hidden into a list somewhere, IS going to be very difficult to reach.

But fortunately, since you say in your question's text that you only care about subclasses of db.Model, that's even easier than gc would allow:

for amodel in db.Model.__subclasses__():
   ...

Just make sure you explicitly ignore such classes you don't care about, such as Expando;-).

Note that this DOES give you only and exactly the CLASSES, not the instances -- there is no similarly easy shortcut if those are what you're really after!

like image 144
Alex Martelli Avatar answered May 02 '26 19:05

Alex Martelli


Classes are defined in modules. Modules are created by an import statement.

Modules are simply dictionaries. If you want, you can use the dir(x) function on a module named x

Or you can use x.__dict__ on a module named x.

like image 22
S.Lott Avatar answered May 02 '26 18:05

S.Lott



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!