Tobias Kienzler
Tobias Kienzler

Reputation: 27403

How to obtain all subclasses (of a specific class) defined by a module?

Given a module module and a class MyClass, how to obtain a list of all subclasses of MyClass defined in module?

Upvotes: 5

Views: 3669

Answers (4)

brunod
brunod

Reputation: 24

maybe try pyclbr module — Python class browser support

http://pymotw.com/2/pyclbr/

Upvotes: 0

alecxe
alecxe

Reputation: 473853

You can use inspect.getmembers(). Assuming you have in mymodule.py:

class A(object):
    pass


class B(A):
    pass


class C(A):
    pass

here's how you can get all subclasses of A:

import inspect
import mymodule
from mymodule import A

def is_subclass(o):
    return inspect.isclass(o) and issubclass(o, A)


print inspect.getmembers(mymodule, predicate=is_subclass)

or, in short lambda form:

print inspect.getmembers(mymodule,  
                         predicate=lambda o: inspect.isclass(o) and \
                                             issubclass(o, A))

Upvotes: 8

Colonel Panic
Colonel Panic

Reputation: 137574

My attempt:

>>> def f(module):
...     things = [getattr(module, x) for x in dir(module)]
...     return [x for x in things if type(x) == type]
...
>>> import datetime
>>> f(datetime)
[<type 'datetime.date'>, <type 'datetime.datetime'>, <type 'datetime.time'>, <type 'datetime.timedelta'>, <type 'datetime.tzinfo'>]

Upvotes: 1

Tobias Kienzler
Tobias Kienzler

Reputation: 27403

classes = ()
for name in dir(module):
    obj = getattr(module, name)
    try:
        # obj.__mro__ raises AttributeError on non-class
        if MyClass in obj.__mro__ and obj is not MyClass:
            classes += (obj,)
        #else:
        #    print name, "is no subclass of", MyClass
    except AttributeError:
        #print name, "is no class"
        pass  # you might of course use an if hasattr(obj, '__mro__') instead

Not pretty, but works. Alternatives are welcome though...

Upvotes: 1

Related Questions