@lru_cache on functions with no arguments

Christian Heimes christian at python.org
Tue Aug 1 09:57:47 EDT 2017


On 2017-08-01 01:31, 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. A lru_cache isn't strictly needed here, but it's convenient to just cache the result. Some examples are here: https://github.com/django/django/pull/8825/files
> 
> I did some profiling and I found that using `@lru_cache(maxsize=None)` on such functions is twice as fast as a standard `@lru_cache()`, apparently because with a `maxsize` the lru_cache code requires a lock acquisition and a fair bit more state to track.
> 
> Am I right in thinking that using `maxsize=None` is best for functions that accept no arguments? Should we even be using a `lru_cache` in such situations, or write our own simple cache decorator instead?

There is a more elegant and faster approach if you use a non-data
descriptor instead of a property or a lru_cache. If you use a non-data
descriptor property, you can even get rid of subsequent function calls.
I dumped some example code in a gist,
https://gist.github.com/tiran/da7d4c43d493c5aa7d7abc4d8a0678a6

Christian




More information about the Python-list mailing list