list classes in package

Guilherme Polo ggpolo at gmail.com
Wed Jan 16 11:23:43 EST 2008


2008/1/16, Diez B. Roggisch <deets at nospam.web.de>:
> Dmitry wrote:
>
> > Hi All,
> >
> > I've trying to develop one Python application, and
> > neet to solve one problem. I need to list all classes defined in one
> > package (not module!).
> >
> > Could anybody please show me more convinient (correct) way to
> > implement this?
>
> Look at the module inspect and it's predicates. Something like
>
>
> for name in dir(module_or_package):
>     if inspect.isclass(getattr(module_or_package, name)):
>        print "%s is a class" % name
>
>
> Diez
> --
> http://mail.python.org/mailman/listinfo/python-list
>

You should be able to adapt this one. You need to pass a directory to
it (warning: directory names including dots will cause you errors):

import os
import sys
import pyclbr

def pkg_modules(package):
    return filter(lambda x: x.endswith(".py"), os.listdir(package))

def module_classes(module):
    dict = pyclbr.readmodule_ex(module, [])
    objs = dict.values()
    objs.sort(lambda a, b: cmp(getattr(a, 'lineno', 0),
                               getattr(b, 'lineno', 0)))

    print module
    for obj in objs:
        if isinstance(obj, pyclbr.Class):
            print "  class %s %s line: %d" % (obj.name, obj.super, obj.lineno)

def pkg_classes(package):
    for module in pkg_modules(package):
        module_classes("%s.%s" % (package, module[:-3]))

if __name__ == "__main__":
    pkg_classes(sys.argv[1])

-- 
-- Guilherme H. Polo Goncalves



More information about the Python-list mailing list