Best way to enumerate classes in a module
nick at craig-wood.com
Thu Jun 25 18:30:03 CEST 2009
Carl Banks <pavlovevidence at gmail.com> wrote:
> On Jun 23, 10:02 pm, Дамјан Георгиевски <gdam... at gmail.com> 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
> >  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?
> You can use module.__dict__.values() (or .itervalues()) to retrieve
> the contents of the module (and of course .keys() if you want names).
> If you want to check the same module that the code appears in, use
> globals() instead of module.__dict__.
> Something makes me think that module.__dict__ was only added to Python
> fairly recently, but I'm not sure.
It exists in python2.1 - I don't have an older python to check at the
> A word of warning (although I would guess you are already aware of
> these issues, but for other readers): this method can't tell the
> difference between a class defined in the module and a class imported
> into it.
> Finally, despite the warning, I think you are ok to use dir() for that
> purpose. It's not likely to change.
And as a double check
>>> import sys
>>> set(sys.__dict__.keys()) == set(dir(sys))
>>> import os
>>> set(os.__dict__.keys()) == set(dir(os))
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list