Best way to enumerate classes in a module

Carl Banks pavlovevidence at
Wed Jun 24 03:49:34 EDT 2009

On Jun 23, 10:02 pm, Дамјан Георгиевски <gdam... at> 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?

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.

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.

Carl Banks

More information about the Python-list mailing list