hash consing
Emile van Sebille
emile at fenx.com
Sat Oct 27 10:21:15 EDT 2001
"John S. Yates, Jr." <john at yates-sheets.org> wrote in message
news:vh6lttk4mkchsk952re68udp4bqqvc1c18 at 4ax.com...
> Is it possible to implement an "immutable" python
> class that maintains a single instance of each unique
> value via hash consing? I know that I can maintain
> the hash table outside of the class, lookup the
> argument tuple for the class instance I want and only
> call the constructor when I the lookup fails. What
> I would really like is to be able to hide that logic
> inside the constructor.
I'm not sure what consing means, but perhaps the code below helps you out.
The intent is that you shadow any cache friendly class with my_class =
Cache(my_class), where friendly means a class without a __call__ method,
with properly referenced class level attributes, and with hashable __init__
args.
HTH,
--
Emile van Sebille
emile at fenx.com
---------
class Eggs:
spam_count = 0
def __init__(self, *args):
self.id = self.__class__.spam_count
self.__class__.spam_count += 1
class Cache:
def __init__(self, klass):
self.klass = klass
self._cache = {}
def __call__(self, *args):
if self._cache.has_key(args):
return(self._cache[args])
else:
retval = self.klass(*args)
self._cache[args] = retval
return retval
Eggs = Cache(Eggs)
a = Eggs(1,2,3)
b = Eggs(1,2,3)
assert a is b
c = Eggs(4,5,6)
assert 1 == c.id
More information about the Python-list
mailing list