473,399 Members | 3,302 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

Get List of Classes

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. Thanks in advance....

DigiO

Jun 26 '06 #1
4 1470
> 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


Jun 26 '06 #2
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


Jun 26 '06 #3
Le lundi 26 juin 2006 17:25, Tim Chase a écrit*:
*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.

Why not :

In [8]: import types, sys

In [9]: isinstance(sys, types.ModuleType)
Out[9]: True

?
Seems rather explicit IMO.

--
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
Jun 26 '06 #4
>> 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.


Why not :

In [8]: import types, sys

In [9]: isinstance(sys, types.ModuleType)
Out[9]: True


Yes...this is the best way to do it. I hadn't explored (or even
noticed, before your reply) the "types" module, which seems to
have a large toolset for doing exactly what I wanted to. Thanks!

A good programming language has users asking "how did I miss
that?" rather than "why can't I make it do what I want?". Yet
another feather in Python's cap.

-tkc


Jun 26 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Darryl B | last post by:
I can not get anywhere on this project I'm tryin to do. I'm not expecting any major help with this but any would be appreciated. The assignment is attached. The problem I'm having is trying to set...
1
by: Chris K | last post by:
I am relatively new to C++ and hope that this question is relevant. I have spent some time at the local library and some time on dejanews, but have no decided to go ahead with my question, since...
1
by: barnesc | last post by:
Hi again, Since my linear algebra library appears not to serve any practical need (I found cgkit, and that works better for me), I've gotten bored and went back to one of my other projects:...
5
by: Kenneth | last post by:
<list> seems to be a powerful structure to store the related nodes in memory for fast operations, but the examples I found are all related to primitive type storage. I'm doing a project on C++...
6
by: Joe | last post by:
I have 2 multi-list boxes, 1 displays course categories based on a table called CATEGORIES. This table has 2 fields CATEGORY_ID, CATEGORY_NAME The other multi-list box displays courses based on...
3
by: moondaddy | last post by:
I wrote my own List class which I use to bind to list controls. this class inherits CollectionBase and implements IBindingList. This class contains a list of business classes such as customers...
7
by: wolfing1 | last post by:
Is there a way to see what CSS classes in a page are not defined? (like if I want to find mispelled class names, etc)
1
by: David Bilsby | last post by:
All Apologies for cross posing this but I am not sure if this is a VC 8 STL bug or simply an invalid use of the iterator. I have a PCI card access class which basically abstracts a third party...
6
by: David C | last post by:
In my business layer, I have Person, and Patient which derives from Person. //base class for all single classes public class BaseItem{} public class Person:BaseItem{} public class...
0
AmberJain
by: AmberJain | last post by:
Windows Autorun FAQs: List of autostart locations Linked from the Original article- "Windows Autorun FAQs: Description". Que: Can you list all the autostart locations for windows? Ans: Here is...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.