@lru_cache on functions with no arguments
tom at tomforb.es
tom at tomforb.es
Tue Aug 1 10:52:30 EDT 2017
> _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.
I did some timings with this as part of my timings above and found it to be significantly slower than lru_cache with the C extension. I had to add `nonlocal` to get `_val` to resolve, which I think kills performance a bit.
I agree with the premise though, it might be worth exploring.
> 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
Thank you! That's an interesting and great idea. It's faster, but not faster than lru-cache with the C extension. I'll investigate further.
More information about the Python-list
mailing list