Get List of Classes
digitalorganics at gmail.com
digitalorganics at gmail.com
Mon Jun 26 11:39:46 EDT 2006
Wow, more than I had asked for, thank you Tim!
I ended up doing this:
def isClass(object):
if 'classobj' in str(type(object)):
return 1
elif "'type'" in str(type(object)):
return 1
else:
return 0
def listClasses():
classes = []
for eachobj in globals().keys():
if isClass(globals()[eachobj]):
classes.append(globals()[eachobj])
print eachobj
return classes
Tim Chase wrote:
> > Is there a method or attribute I can use to get a list of
> > classes defined or in-use within my python program? I tried
> > using pyclbr and readmodule but for reason that is dogslow.
>
> Well, given that so much in python is considered a class, the
> somewhat crude code below walks an object/module and emits
> details regarding what's going on. I couldn't find any nice
> method for determining if a variable referenced a module other
> than checking to see if that item had both a "__file__" and a
> "__name__" attribute. Likewise, the check for whether something
> is an object is a bit crude.
>
>
> >>> def inspect(thing, name = '', indent=0):
> ... if hasattr(thing, "__file__") and hasattr(thing, "__name__"):
> ... #assume it's a module
> ... print "%sModule %s" % ("\t" * indent, thing.__name__)
> ... for subthing in dir(thing):
> ... objname = ".".join([name,
> subthing]).lstrip(".")
> ... inspect(eval(objname),
> ... objname, indent+1)
> ... elif isinstance(thing, object):
> ... print "%s%s is an object" % ("\t" * indent, name)
> ...
> >>> import m1
> >>> # m1 is a junk module that references module "m2" and has
> >>> # some junk classes in it
> >>> inspect(m1, "m1")
> Module m1
> m1.M1Class is an object
> m1.M1ObjectClass is an object
> m1.__builtins__ is an object
> m1.__doc__ is an object
> m1.__file__ is an object
> m1.__name__ is an object
> Module m2
> m1.m2.M2Class is an object
> m1.m2.M2ObjectClass is an object
> m1.m2.__builtins__ is an object
> m1.m2.__doc__ is an object
> m1.m2.__file__ is an object
> m1.m2.__name__ is an object
>
>
>
> You could also filter out builtin object properties by wrapping
> that last print statement in something like
>
> if not name.startswith("_"): print ...
>
> which might cut down on some of the noise.
>
> Just a few ideas.
>
> -tkc
More information about the Python-list
mailing list