Keeping track of subclasses and instances?

Andreas Kraemer akraemer at
Thu Oct 11 07:49:23 CEST 2007

On Oct 10, 6:19 pm, Karlo Lozovina <_kar... at> wrote:
> Larry Bates wrote:
> > I'm not completely sure I understand the question but here goes.
> > Instances of
> > classes are classes can be stored in lists or dictionaries.  In lists you
> > reference them via their index (or iterate over them) and in dictionaries
> > you can give them a name that is used as a key.
> I wish if it were that simple :).
> Here is a longer description - I have a function that given input creates a
> custom class and returns it back. The user is free to subclass that (even
> more, he should do that), and of course he will make instances of those
> subclasses. Now, my question is how to keep track of subclasses and their
> instances, without the need for user interaction (appending them to a list,
> or adding to dictionary)?
> Thanks,
> --
> Karlo Lozovina - Mosorclass Meta(type):

What about the following solution?

class Meta(type):
  def __new__(mcl,*args,**kw):
    class_ = super(Meta,mcl).__new__(mcl,*args,**kw)
    class_._instances = []
    return class_
  _classes = []

def factory():
  class Class(object):
    __metaclass__ = Meta
    def __new__(cls,*args,**kw):
      instance = super(Class,cls).__new__(cls,*args,**kw)
      return instance
  return Class

>>> A = factory()
>>> class B(A): pass
>>> a = A()
>>> b = B()
>>> Meta._classes
[<class 'meta.Class'>, <class '__main__.B'>]
>>> A._instances
[<meta.Class object at 0xb7dbb08c>]
>>> B._instances
[<__main__.B object at 0xb7dbb0ec>]

So, you see that you can access all classes, their subclasses, and
instances from Meta.

Of course in a more elaborate version _classes and _instances should
store weak references, so that classes and instances can actually be
deleted. I also haven't explored under which circumstances this can
break ...

I can imagine different use cases for this, (though they certainly are
non-standard :-)). I once contemplated the (toy-) implementation of a
frame-based knowledge representation system using Python's object
model, where one definitely needs classes to keep track of their
instances ...


More information about the Python-list mailing list