Python – anyone have a memoizing decorator that can handle unhashable arguments?

Here is the example in Alex Martelli Python Cookbook that show how to create a memoize decorator using cPickle for function that take mutable argument (original version) : import cPickle class MemoizeMutable: def __init__(self, fn): self.fn = fn self.memo = {} def __call__(self, *args, **kwds): import cPickle str = cPickle.dumps(args, 1)+cPickle.dumps(kwds, 1) if not self.memo.has_key(str): … Read more

What type to use to store an in-memory mutable data table in Scala?

You could use a mutable.Map[TupleN[A1, A2, …, AN], R] , or if memory is a concern, a WeakHashMap[1]. The definitions below (built on the memoization code from michid’s blog) allow you to easily memoize functions with multiple arguments. For example: import Memoize._ def reallySlowFn(i: Int, s: String): Int = { Thread.sleep(3000) i + s.length } … Read more

Caching class attributes in Python

3.8 ≤ Python @property and @functools.lru_cache have been combined into @cached_property. import functools class MyClass: @functools.cached_property def foo(self): print(“long calculation here”) return 21 * 2 3.2 ≤ Python < 3.8 You should use both @property and @functools.lru_cache decorators: import functools class MyClass: @property @functools.lru_cache() def foo(self): print(“long calculation here”) return 21 * 2 This answer … Read more