How do you get all classes defined in a module but not imported?

Davy8 picture Davy8 · Apr 2, 2011 · Viewed 25k times · Source

I've already seen the following question but it doesn't quite get me where I want: How can I get a list of all classes within current module in Python?

In particular, I do not want classes that are imported, e.g. if I had the following module:

from my.namespace import MyBaseClass
from somewhere.else import SomeOtherClass

class NewClass(MyBaseClass):
    pass

class AnotherClass(MyBaseClass):
    pass

class YetAnotherClass(MyBaseClass):
    pass

If I use clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass) like the accepted answer in the linked question suggests, it would return MyBaseClass and SomeOtherClass in addition to the 3 defined in this module.

How can I get only NewClass, AnotherClass and YetAnotherClass?

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · Apr 2, 2011

Inspect the __module__ attribute of the class to find out which module it was defined in.