Listing subtypes

Ben Finney bignose+hates-spam at benfinney.id.au
Wed Nov 28 19:04:56 EST 2007


Samuel <knipknap at gmail.com> writes:

> I remember seeing an easy way to list all subtypes of a specific type
> but I haven't been able to find it anymore. What I am trying to do is
> this: Given a class, get a list of all classes that derive from it.
> Pretty much like __mro__ but downwards rather then upwards. Any ideas?

A class knows its parents; it doesn't know its children. (Or, in other
words, children need to know who their parents are, but aren't
required to notify their parents about anything.)

To find the latter, you need to go find those children yourself and
ask them whether the class you're interested in is an ancestor.

Untested code::

    classes = [obj for obj in globals() if type(obj) == type]
    ancestor = FooClass
    descendants = [cls for cls in classes if issubclass(cls, ancestor)]

Substitute the appropriate namespace for 'globals()', and the class
you're interested in for 'FooClass'.

-- 
 \          "If you can't beat them, arrange to have them beaten."  -- |
  `\                                                     George Carlin |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list