Singleton-like pattern

Michele Simionato mis6 at pitt.edu
Fri Aug 1 18:15:34 CEST 2003


pedro.werneck at bol.com.br (Pedro Werneck) wrote in message news:<ef72fb2b.0307312003.6717cc9e at posting.google.com>...
> I need to implement an object that behaves just like imutable objects,
> like int, str and tuple: if you create two objects with the same value
> at the same time, you get the same object, like a singleton, but
> instead of storing a unique object, store a set of objects, with no
> duplicates. I don't know if this is a common pattern (and if there's a
> name for it), but I remember reading something about it some time
> ago... the ASPN cookbook has some similar patterns, but none works for
> me...
> 
> I know there are several ways to implement this, but I think this
> metaclass approach is more elegant than using __new__ and
> inheritance... at least it solves my problem (I'm working on a card
> game) but I am sure that there are better ways to do it... I could not
> find any other value suitable as a key and using str(args) + str(kwds)
> is ugly and easy to break...
> 
> 
> class MultiSingleton(type):
>     def __call__(cls, *args, **kwds):
>         cache = cls.__dict__.get('__cache__')
>         if cache is None:
>             cls.__cache__ = cache = {}
>         tag = str(args) + str(kwds)
>         if tag in cache:
>             return cache[tag]
>         obj = object.__new__(cls)
>         obj.__init__(*args, **kwds)
>         cache[tag] = obj
>         return obj
> 
> 
> Any help will be much appreciated... thanks in advance
> 
> Pedro Werneck

"memoize" is a possible name for this. Notice that the metaclass is a
bit of overkill, you may well use a simple function for this job. 
About the issue of finding a suitable key, in the same situation I have 
used the tuple (args,kw) as key. But me too I would like to ask if this is a
good idea. What's the custom solution for getting a good key from
a dictionary ?


                           Michele




More information about the Python-list mailing list