@lru_cache on functions with no arguments
Paul Moore
p.f.moore at gmail.com
Tue Aug 1 09:48:38 EDT 2017
On Tuesday, 1 August 2017 00:31:52 UTC+1, t... at tomforb.es wrote:
> 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?
It seems like overkill to use lru_cache for this case - it's designed to map arguments to results, so it makes little sense when there are no arguments. It's also got LRU arglist management and thread safety overheads, so there's a lot of unneeded overhead for this usage.
_sentinel = object()
_val = _sentinel
def val():
if _val is _sentinel:
# Calculate _val
return _val
seems entirely sufficient for this case. Write a custom decorator if you use the idiom often enough to make it worth the effort.
Paul
More information about the Python-list
mailing list