Python - Iterating Through All Classes

How can I iterate over the list of all classes loaded into memory? I'm going to do this for a backup looking for all classes inheriting from db.Model (Google App Engine).

Thanks, Neil Walters

+2


source to share


3 answers


In "normal" Python, you can reach all objects using the gc.getobjects()

standard library module function gc

; then they are very easy to loop over them, checking which ones are classes (not instances or whatever), I suppose you mean instances of classes, but you can very easily get the classes yourself if that's really what what you want), etc.

Unfortunately, a module gc

in App Engine does NOT implement getobjects

- which makes it extremely difficult to reach ALL classes. For example, a class created when called:

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

      

and hide in the list somewhere, it is very difficult to reach.



But fortunately, since you are saying in your text question that you only care about subclasses db.Model

, which is even easier than gc

it would allow:

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

      

Just make sure you explicitly ignore classes that you don't need, like Expando

; -).

Note that this only gives you exactly CLASSES, not instances - there is no similarly simple combination if that's what you really are!

+9


source


Classes are defined in modules. Modules are created by the operator import

.

Modules are just dictionaries. If you want you can use a function dir(x)

in a module namedx



Or you can use x.__dict__

in a module named x

.

+2


source


Based on S.Lott's answer: This works if I omit "if issubclass", except when I get classes that I don't want.

  import dbModels 
  self.response.out.write("<br/><br/>Class Names:</br/>")
  for item in dbModels.__dict__:
      if issubclass(item, db.Model):
         self.response.out.write("<br/>" + item) 

      

The above gives an error:

TypeError: issubclass () arg 1 must be a class

So he wants the class name to be parm, not the object name, obviously.

Building on Alex's answer, this worked great:

  self.response.out.write("<br/><br/>Class Names Inheriting from db.Model:</br/>")
  for item in db.Model.__subclasses__():
       self.response.out.write("<br/>" + item.__name__)

      

Thanks to both!

Nile

0


source







All Articles