[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

list classes in package

Dmitry

1/16/2008 2:11:00 PM

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?

Thanks,
Dmitry
2 Answers

Diez B. Roggisch

1/16/2008 3:37:00 PM

0

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

Guilherme Polo

1/16/2008 4:24:00 PM

0

2008/1/16, Diez B. Roggisch <deets@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/p...
>

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