P
Pedro Werneck
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
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