Listing subtypes

S

Samuel

Hi,

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?

-Samuel
 
B

Ben Finney

Samuel said:
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'.
 
B

Ben Finney

Diez B. Roggisch said:
Ben said:
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.)

Not right. These special children are under a more demanding
goverment.

[...]
print A.__subclasses__()

Thanks. I've now learned my recommended daily dosage of one new thing.
 
P

Paddy

Not right. These special children are under a more demanding
goverment.
[...]
print A.__subclasses__()

Thanks. I've now learned my recommended daily dosage of one new thing.

--
\ "Unix is an operating system, OS/2 is half an operating system, |
`\ Windows is a shell, and DOS is a boot partition virus." -- |
_o__) Peter H. Coffin |
Ben Finney

From http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-02/4172.html
it seems to be an undocumented feature. Read the post and decide for
yourself if you want to depend on it.

- Paddy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top