Memoize, but clear cache when last function call returns. Suitable for dynamic programming.
Python, 37 lines
Memoization as presented in Recipe 52201 uses ever-increasing amounts of memory, since items are never evicted from the cache. In some use cases (e.g. dynamic programming), it is acceptable to clear the cache when the last function call returns. The memoize() function given in this recipe does that.
This recipe handles both mutable and immutable arguments.