On Feb 9, 1:38 am, Freek Dijkstra <[EMAIL PROTECTED]> wrote: > J Peyret wrote: [...] > I'll use __metaclass__ solution. Here is my (non-threaded) version:
Great! There's nothing voodoo about metaclasses. > class RDFObject(object): > _cache = {} # class variable is shared among all RDFObject > instances > class __metaclass__(type): > def __call__(cls, *args, **kwargs): > return cls.__new__(cls, *args, **kwargs) > def __new__(cls, uri, *args, **kargs): > if uri not in cls._cache: > obj = object.__new__(cls) > cls._cache[uri] = obj > obj.__init__(uri, *args, **kargs) > return cls._cache[uri] > def __init__(self, uri): > self.uri = uri > print self.__class__, uri > # ... [...] > Perhaps indeed the try...except KeyError is even prettier (no idea > about speed, but let's rename this thread if we want to discuss > performance measurements). I would go for something like (untested): def __new__(cls, uri, *args, **kwargs): obj = cls._cache.get(uri, None): if obj is None: obj = cls._cache[uri] = object.__new__(cls) obj.__init__(uri, *args, **kwargs) return obj It doesn't look up the cache sho much and I think reads just as well. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list