Keeping track of subclasses and instances?

Andreas Kraemer akraemer at sbcglobal.net
Thu Oct 11 01:49:23 EDT 2007


On Oct 10, 6:19 pm, Karlo Lozovina <_kar... at mosor.net> 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)
    mcl._classes.append(class_)
    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)
      cls._instances.append(instance)
      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 ...

Cheers,
Andreas











More information about the Python-list mailing list