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

Chris Angelico rosuav at gmail.com
Mon Dec 7 16:06:59 EST 2015


On Sat, Dec 5, 2015 at 8:44 AM, Bill Winslow <bunslow at gmail.com> wrote:
> def deterministic_recursive_calculation(input, partial_state=None):
>     condition = do_some_calculations(input)
>     if condition:
>         return deterministic_recursive_calculation(reduced_input,
> some_state)
>
> Basically, in calculating the results of the subproblem, the subproblem can
> be calculated quicker by including/sharing some partial results from the
> superproblem. (Calling the subproblem without the partial state still gives
> the same result, but takes substantially longer.)
>
> I want to memoize this function for obvious reasons, but I need the
> lru_cache to ignore the partial_state argument, for its value does not
> affect the output, only the computation expense.

Coming right back to the beginning here...

Is there a reason the some_state argument is being passed around,
instead of being global? If the result of the function depends only on
reduced_input and not on some_state, then wouldn't it be possible to
make use of state from an entirely separate call, not just the current
one? (And if you _can't_ make use of some_state from an unrelated
call, then it _does_ affect the call, and it needs to be incorporated
into the cache key.) ISTM this should be exactly as global as the
cache itself.

ChrisA


More information about the Python-ideas mailing list