@lru_cache on functions with no arguments
Terry Reedy
tjreedy at udel.edu
Tue Aug 1 11:05:38 EDT 2017
On 8/1/2017 7:06 AM, Matt Wheeler wrote:
> On Tue, 1 Aug 2017 at 02:32 Terry Reedy <tjreedy at udel.edu> wrote:
>
>> On 7/31/2017 7:31 PM, tom at tomforb.es wrote:
>>> As part of the Python 3 cleanup in Django there are a fair few uses of
>> @functools.lru_cache on functions that take no arguments.
>>
>> This makes no sense to me. If the function is being called for
>> side-effects, then it should not be cached. If the function is being
>> called for a result, different for each call, calculated from a changing
>> environment, then it should not be cached. (Input from disk is an
>> example.) If the function returns a random number, or a non-constant
>> value from an oracle (such as a person), it should not be cached. If
>> the function returns a constant (possible calculated once), then the
>> constant should just be bound to a name (which is a form of caching)
>> rather than using the overkill of an lru cache. What possibility am I
>> missing?
>>
>
> A function which is moderately expensive to run, that will always return
> the same result if run again in the same process, and which will not be
> needed in every session.
In initialization section:
answer = None
Somewhere else:
answer = expensive_calculaton() if answer is None else answer
The conditional has to be cheaper than accessing lru cache. There can
be more than one of these.
--
Terry Jan Reedy
More information about the Python-list
mailing list