tags:

views:

89

answers:

3

Is there a way to flag class declarations so that later you can get a list of them flagged?

Or a way to get all classes starting with a certain string ?

Or all classes that are a subclass of a specific class?

+3  A: 
Stephan202
bobince: yeah, it just dawned on me that it didn't work in 2.x because I forgot to use new style classes...
Stephan202
This all looks fine for Python 2.x too... class decorators are new in 2.6.
bobince
Hah, now it looks like I saw into the future and knew you were going to comment ;)
Stephan202
Thanks for the quick answer. I'll probably use is subclass minus T solution. Thanks!
Pykedout
+1  A: 

You can also use metaclasses to collect up the classes as they are defined:

class AllSeeingMetaClass(type):
    # This will be a list of all the classes that use us as a metaclass.
    the_classes = []

    def __new__(meta, classname, bases, classDict):
        # Invoked as new classes are defined.
        print "Defining %r" % classname
        new_class = type.__new__(meta, classname, bases, classDict)
        meta.the_classes.append(new_class)
        return new_class


class MyBase(object):
    # A base class that pulls in our metaclass.
    __metaclass__ = AllSeeingMetaClass


class Cat(MyBase):
    def __init__(self):
        pass

class Dog(MyBase):
    def __init__(self):
        pass

print AllSeeingMetaClass.the_classes

prints:

Defining 'MyBase'
Defining 'Cat'
Defining 'Dog'
[<class '__main__.MyBase'>, <class '__main__.Cat'>, <class '__main__.Dog'>]
Ned Batchelder
+1  A: 

To get a list of subclasses of your class from within itself, use the __subclasses__ method from the parent class.

>>>class Parent(object):
...    pass
...
>>>class Child(Parent):
...    pass
...
>>>Parent.__subclasses__()
>>>[<class '__main__.Child'>]

Unfortunately there is a dearth of documentation on this method.

Don Spaulding