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

Peter Otten __peter__ at web.de
Wed Oct 5 19:24:07 CEST 2005


marduk wrote:

> On Wed, 2005-10-05 at 12:56 -0400, Jonathan LaCour wrote:
>> > class Spam(object):
>> >     cache = {}
>> >     def __new__(cls, x):
>> >         if cls.cache.has_key(x):
>> >             return cls.cache[x]
>> >     def __init__(self, x):
>> >         self.x = x
>> >         self.cache[x] = self
>> >
>> > a = Spam('foo')
>> > b = Spam('foo')
>> >
>> > Well, in this case a and b are identical... to None!  I assume this is
>> > because the test in __new__ fails so it returns None, I need to then
>> > create a new Spam.. but how do I do that without calling __new__
>> > again?
>> > I can't call __init__ because there's no self...
>> >
>> >
>> 
>> Oops, you forgot to return object.__new__(cls, x) in the case the
>> object isn't in the cache.  That should fix it.
> 
> Okay, one more question... say I then
> 
> c = Spam('bar')
> del a
> del b
> 
> 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).

Use a weakref.WeakValueDictionary as the cache instead of a normal dict.

Peter




More information about the Python-list mailing list