I'm trying to writing a generic metaclass for tracking subclasses
Since I want this to be generic, I didn't want to hardcode any class name within this metaclass, therefore I came up with a function that generates the proper metaclass, something like:
def make_subtracker(root):
class SubclassTracker(type):
def __init__(cls, name, bases, dct):
print('registering %s' % (name,))
root._registry.append(cls)
super(SubclassTracker, cls).__init__(name, bases, dct)
return SubclassTracker
This way I could invoke it to generate a metaclass for a specific root class with:
__metaclass__ = make_subtracker(Root)
Here is where I bump into a problem. I cannot do this:
class Root(object):
_registry = []
__metaclass__ = make_subtracker(Root)
...because Root
is not defined yet when I use make_subtracker(Root)
. I tried adding the metaclass attribute later, so that at least it can be applied in subclasses:
class Root(object):
_registry = []
Root.__metaclass__ = make_subtracker(Root)
...but this doesn't work. metaclass has a special processing when the class definition is read, as defined in http://docs.python.org/reference/datamodel.html#customizing-class-creation
I'm looking for suggestions in order to do this (either change a class' metaclass at runtime in a way that it is applied to its subclasses, or any other alternative).
Here's something I've been playing around with (that works):
Python does this automatically for new-style classes, as mentioned in this answer to the similar queston How can I find all subclasses of a given class in Python? here.
I think you want something like this (untested):
Then, for Python 2, you can invoke it like:
for Python 3
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.