Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Use lru_cache decorator on memoize function #406

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 25, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 4 additions & 10 deletions utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,13 +270,10 @@ def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
# Misc Functions


# TODO: Use functools.lru_cache memoization decorator


def memoize(fn, slot=None):
def memoize(fn, slot=None, maxsize=32):
"""Memoize fn: make it remember the computed value for any argument list.
If slot is specified, store result in that slot of first argument.
If slot is false, store results in a dictionary."""
If slot is false, use lru_cache for caching the values."""
if slot:
def memoized_fn(obj, *args):
if hasattr(obj, slot):
Expand All @@ -286,12 +283,9 @@ def memoized_fn(obj, *args):
setattr(obj, slot, val)
return val
else:
@functools.lru_cache(maxsize=maxsize)
def memoized_fn(*args):
if args not in memoized_fn.cache:
memoized_fn.cache[args] = fn(*args)
return memoized_fn.cache[args]

memoized_fn.cache = {}
return fn(*args)

return memoized_fn

Expand Down