Enumerating Classes in Modules

Carlos Ribeiro carribeiro at gmail.com
Sat Nov 20 18:11:26 EST 2004


On Sun, 21 Nov 2004 03:51:33 +1000, Nick Coghlan <ncoghlan at email.com> wrote:
> Rob Snyder wrote:
> 
> 
> > Just in case anyone "follows in my footsteps" and has the same problem I did
> > - Jeff's answer is pretty much dead on. The only stumbling block I had was
> > that the dir() returns a list of strings representating the name of the
> > attributes, and includes things that are not class definitions (e.g.
> > '--builtins--'). So two modifications are necessary:
> >
> > 1 - use the getattr() function with each item returned by dir() to actually
> > load the class object
> > 2 - use type() to determine if it really it really is a classobj
> 
> I would suggest "hasattr" with the method you're interested in as a better way
> to perform step 2. That should cover both old and new style classes quite happily.

Using hasattr() is better than checking the type. But a better, and
more generic solution, is to use the adapt framework. I've written a
short tutorial on adaptation. It's at my blog:

http://pythonnotes.blogspot.com/2004/11/what-is-adaptation.html

In this case, the idea is: get every type you can find, and try to
adapt it to the interface you want. If the adaptation is succesfull,
the result is the object you want.

Also, if you prefer to keep doing things the "old way", a possibility
is to use isclass and issubclass.

issubclass is a builtin. You can just call it, and it will tell you if
an object is a descendant of the given class. But it will raise an
exception if the argument is *not* a class. It belongs to the BAFP -
"better to ask for forgiveness than permission" coding style.

If you prefer to code in the LBYL - "look before you leap" - style,
then you can use isclass, from the inspect module.

from inspect import isclass
if isclass(x) and issubclass(x, myclass):
    ...


-- 
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: carribeiro at gmail.com
mail: carribeiro at yahoo.com



More information about the Python-list mailing list