Search code examples
pythonpython-2.7superclass

Get classes derived from specific class in the module


I need to get classes from the module that derives only from specific TargetClass:

import mymodule as t
for att in dir(t):
   someclass = getattr(t, att)
   if isinstance(someclass, TargetClass):
       print ("Do something with %s" % att)

Well... This is not work, so i need to create instances, and catching exceptions, if module's attribute is not callable:

import mymodule as t
for att in dir(t):
   someclass = getattr(t, att)
   try:
       if isinstance(someclass(), TargetClass):
           print ("Do something with %s" % att)
   except:
       pass

So how do i get only those classes from mymodule, that is subclasses of some TargetClass, without creation of instances and catching exception?


Solution

  • You can use issubclass instead of isinstance, but essentially you'll have the same problem, as the 1st argument to issubclass must be a class. So you can combine them:

    import mymodule as t
    for att in dir(t):
       someclass = getattr(t, att)
       if isinstance (someclass, type) and issubclass(someclass, TargetClass):
           print ("Do something with %s" % att)