how to keep collection of existing instances and return one on instantiation

Laszlo Zsolt Nagy gandalf at designaproduct.biz
Wed Oct 5 13:36:51 EDT 2005


>I've removed all references to the object, except for the cache.  Do I
>have to implement my own garbage collecting is or there some "magical"
>way of doing this within Python?  I pretty much want to get rid of the
>cache as soon as there are no other references (other than the cache).
>
Store weak references to instances.

from weakref import ref

class Spam(object):
    cache = {}
    def __new__(cls, x):
        instance = None        
        if cls.cache.has_key(x):
            instance = cls.cache[x]()
        if instance is None:
            instance  = object.__new__(cls, x)
            cls.cache[x] = ref(instance )
        return instance
    def __init__(self, x):
        self.x = x

Then:

 >>> a = Spam('foo')
 >>> b = Spam('foo')
 >>> a is b
True
 >>> print Spam.cache
{'foo': <weakref at 00A1F690; to 'Spam' at 00A2A650>}
 >>> del a
 >>> del b
 >>> print Spam.cache
{'foo': <weakref at 00A1F690; dead>}
 >>>

Well, of course this is still not thread safe, and weak references will 
use some memory (but it can be much less expensive).
You can grabage collect dead weak references periodically, if you wish.

Best,

   Les





More information about the Python-list mailing list