Skip to content

Commit f624415

Browse files
lucasmouranorvig
authored andcommitted
Use lru_cache decorator on memoize function (aimacode#406)
1 parent df9d7d5 commit f624415

File tree

1 file changed

+4
-10
lines changed

1 file changed

+4
-10
lines changed

utils.py

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -270,13 +270,10 @@ def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
270270
# Misc Functions
271271

272272

273-
# TODO: Use functools.lru_cache memoization decorator
274-
275-
276-
def memoize(fn, slot=None):
273+
def memoize(fn, slot=None, maxsize=32):
277274
"""Memoize fn: make it remember the computed value for any argument list.
278275
If slot is specified, store result in that slot of first argument.
279-
If slot is false, store results in a dictionary."""
276+
If slot is false, use lru_cache for caching the values."""
280277
if slot:
281278
def memoized_fn(obj, *args):
282279
if hasattr(obj, slot):
@@ -286,12 +283,9 @@ def memoized_fn(obj, *args):
286283
setattr(obj, slot, val)
287284
return val
288285
else:
286+
@functools.lru_cache(maxsize=maxsize)
289287
def memoized_fn(*args):
290-
if args not in memoized_fn.cache:
291-
memoized_fn.cache[args] = fn(*args)
292-
return memoized_fn.cache[args]
293-
294-
memoized_fn.cache = {}
288+
return fn(*args)
295289

296290
return memoized_fn
297291

0 commit comments

Comments
 (0)