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

marduk usenet at marduk.letterboxes.org
Wed Oct 5 19:06:35 CEST 2005


On Wed, 2005-10-05 at 12:56 -0400, Jonathan LaCour wrote:
> Oops, you forgot to return object.__new__(cls, x) in the case the  
> object isn't in the cache.  That should fix it. 

Ahh, that did it.  I didn't even think of calling object...

so the new class looks like:

class Spam(object):
    cache = {}
    def __new__(cls, x):
        if cls.cache.has_key(x):
            return cls.cache[x]
        else:
            new_Spam = object.__new__(cls, x)
            cls.cache[x] = new_Spam
            return new_Spam
    def __init__(self, x):
        self.x = x

a = Spam(2)
b = Spam(2)

a == b # => True
id(a) == id(b) # => True

Thanks for all your help.




More information about the Python-list mailing list