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

Serhiy Storchaka storchaka at gmail.com
Mon Dec 7 08:31:26 EST 2015


On 07.12.15 02:41, Michael Selik wrote:
> On Sat, Dec 5, 2015 at 6:11 PM Serhiy Storchaka
> <storchaka at gmail.com
> <mailto:storchaka at gmail.com>> wrote:
>
>     On 04.12.15 23:44, Bill Winslow wrote:
>      > def deterministic_recursive_calculation(input, partial_state=None):
>      >      condition = do_some_calculations(input)
>      >      if condition:
>      >          return deterministic_recursive_calculation(reduced_input,
>      > some_state)
>      >
>      > 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.
>
>     Memoize a closure.
>
>     def deterministic_calculation(input):
>           some_state = ...
>           @lru_cache()
>           def recursive_calculation(input):
>               nonlocal some_state
>               ...
>               return recursive_calculation(reduced_input)
>           return recursive_calculation(input)
>
>
> This would provide the dynamic programming aspect for the recursion, but
> not cache across successive calls to the outer function. It does look
> cleaner than the OO version.

Decorate the outer function too.




More information about the Python-ideas mailing list