Keeping track of subclasses and instances?

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Thu Oct 11 13:13:52 EDT 2007


George Sakkis a écrit :
(snip)

> Anyway, here's something to get you
> started; all a user has to do is derive (directly or indirectly) from
> InstanceTracker and, if a class C defines __init__,
> super(C,self).__init__() should be called explicitly:

Actually, you don't even need that restriction - just move the tracking 
code from __init__ to __new__.

> 
> from collections import deque
> from weakref import WeakKeyDictionary
> 
> class InstanceTracker(object):
       def __new__(cls, *args, **kw):
           try:
                all = cls.__dict__['__instances__']
           except KeyError:
                cls.__instances__ = all = WeakKeyDictionary()
           self = super(InstanceTracker, self).__new__(cls)
           all[self] = None
           return self

(NB : untested)



More information about the Python-list mailing list