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?
You can use
issubclassinstead ofisinstance,but essentially you’ll have the same problem, as the 1st argument to
issubclassmust be a class. So you can combine them: