Best way to enumerate classes in a module

Peter Otten __peter__ at web.de
Wed Jun 24 02:37:54 EDT 2009


Дамјан Георгиевски wrote:

> I need to programmaticaly enumerate all the classes in a given module.
> Currently I'm using dir(module) but the Notice on the documentation page
> [1]  says "dir() is supplied primarily as a convenience for use at an
> interactive prompt" so that kind of scares me.
> 
> Is there a better approach?
> 
> If there is, how do I get all the classes of the current module?

inspect.getmembers(module, inspect.isclass), but this uses dir() internally.
You may have to remove imported classes:

>>> def getclasses(module):
...     def accept(obj):
...             return inspect.isclass(obj) and module.__name__ == 
obj.__module__
...     return [class_ for name, class_ in inspect.getmembers(module, 
accept)]
...
>>> getclasses(inspect)
[<class 'inspect.ArgInfo'>, <class 'inspect.ArgSpec'>, ...]

Peter




More information about the Python-list mailing list