Python - Iterating Through All Classes
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!
source to share
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
source to share