I\'m trying to write a generic metaclass to track subclasses
Since I want this to be generic, I didn\'t want to hardcode any class name within this metaclass, therefore
I think you want something like this (untested):
class SubclassTracker(type):
def __init__(cls, name, bases, dct):
if not hasattr(cls, '_registry'):
cls._registry = []
print('registering %s' % (name,))
cls._registry.append(cls)
super(SubclassTracker, cls).__init__(name, bases, dct)
Then, for Python 2, you can invoke it like:
class Root(object):
__metaclass__ = SubclassTracker
for Python 3
class Root(object, metaclass=SubclassTracker):
Note that you don't need to stick the _registry
attribute on there because stuff like that is what metaclasses are for. Since you already happen to have one laying around... ;)
Note also that you might want to move the registration code into an else
clause so that the class doesn't register itself as a subclass.