Best way to enumerate classes in a module

Michele Simionato michele.simionato at gmail.com
Fri Jun 26 11:56:15 CEST 2009


On Jun 24, 7:07 pm, Terry Reedy <tjre... at udel.edu> wrote:
> Дамјан Георгиевски 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.
>
> That notice primarily refers to the fact that the special names (of
> __xxx__ form) returned are implementation and version dependent, and may
> not be complete in the sense that dir(ob) may not return __xyz__ even
> though ob.__xyz__ exists and can be retrieved.
>
> If you are only interested in regular-name attribute of ob, let your
> fear fly away.

There are rather special cases (not your case) where dir does not
retrieve
all the names to which an object can respond. In particular this
happens
for class objects:
In [1]: class C(object): pass
   ...:

In [2]: dir(C)
Out[2]:
['__class__',
 '__delattr__',
 '__dict__',
 '__doc__',
 '__getattribute__',
 '__hash__',
 '__init__',
 '__module__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__str__',
 '__weakref__']


Notice the absense of the special names __name__, __mro__,
__subclasses__ and also mro, which
is not special. All these names are defined on the metaclass type and
C responds to them,
but they are not retrieved by dir.



More information about the Python-list mailing list