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

marduk usenet at marduk.letterboxes.org
Wed Oct 5 18:20:06 CEST 2005


I couldn't think of a good subject..

Basically, say I have a class

class Spam:
    def __init__(self, x):
        self.x = x


then if I create two instances:

a = Spam('foo')
b = Spam('foo')

a == b # False

What I *really* want is to keep a collection of all the Spam instances,
and if i try to create a new Spam instance with the same contructor
parameters, then return the existing Spam instance.  I thought new-style
classes would do it:

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...

So what is the best/preferred way to do this?




More information about the Python-list mailing list