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

Jonathan LaCour jonathan-lists at cleverdevil.org
Wed Oct 5 12:56:18 EDT 2005


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

Jonathan
http://cleverdevil.org





More information about the Python-list mailing list