[Python-ideas] Using functools.lru_cache only on some arguments of a function

Franklin? Lee leewangzhong+python at gmail.com
Fri Dec 11 20:19:42 EST 2015


By the way, there are other usecases for ignoring arguments for
caching. For example, dynamic programming where the arguments are the
indices of a sequence, or some other object (tree?) which isn't a
recursive argument. I recommend that those also be done with a closure
(separating the recursive part from the initial arguments), but I
think it's worth considering an lru_cache implementation for students
who haven't learned to, er, abuse closures. Unless someone thinks a
recipe can/should be added to the docs.

On Fri, Dec 11, 2015 at 8:01 PM, Franklin? Lee
<leewangzhong+python at gmail.com> wrote:
> Solutions:
> 1. Rewrite your recursive function so that the partial state is a
> nonlocal variable (in the closure), and memoize the recursive part.
> 2. Attach the state to the function, rather than passing it as a
> parameter. (Also suggested in this comment:
> https://www.reddit.com/r/learnpython/comments/3v75g4/using_functoolslru_cache_only_on_some_arguments/cxr7cnp)
> 3. Wrap the state in a class for which __eq__ is defined to say that
> all instances of it are the same, and __hash__ always returns a
> constant (say, the id of the class).

(What's the etiquette for adding onto your own email? I snipped most
of it for the kb bloat.)


More information about the Python-ideas mailing list