Singleton-like pattern

Bengt Richter bokr at oz.net
Fri Aug 1 21:27:01 CEST 2003


On 1 Aug 2003 09:15:34 -0700, mis6 at pitt.edu (Michele Simionato) wrote:

>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):
   class MultiSingleton(object):
>>     def __call__(cls, *args, **kwds):
       def __new__(cls, *args, **kwds):
>>         cache = cls.__dict__.get('__cache__')
>>         if cache is None:
>>             cls.__cache__ = cache = {}
>>         tag = str(args) + str(kwds)
           tag = '%r%r'% (args, kwds)   # might be an alternative
>>         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.
Why not just change as above, and sublass to inherit the behavior
(and create subclass-specific caches) ?
 
>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 ?
Does (args,kw) work in general? IWT you could easily get something unhashable?
IWT using a tuple of actual args may also be a bad idea since it would prevent callers'
temp args from being garbage collected. I use repr to avoid that, maybe mistakenly?

Regards,
Bengt Richter




More information about the Python-list mailing list