擅长:python、mysql、java
<p>如果您不想使用任何第三个库,您可以在昂贵的函数中再添加一个参数:<code>ttl_hash=None</code>。这个新参数被称为“时间敏感哈希”,其唯一目的是影响<code>lru_cache</code>。</p>
<p>例如:</p>
<pre><code>from functools import lru_cache
import time
@lru_cache()
def my_expensive_function(a, b, ttl_hash=None):
del ttl_hash # to emphasize we don't use it and to shut pylint up
return a + b # horrible CPU load...
def get_ttl_hash(seconds=3600):
"""Return the same value withing `seconds` time period"""
return round(time.time() / seconds)
# somewhere in your code...
res = my_expensive_function(2, 2, ttl_hash=get_ttl_hash())
# cache will be updated once in an hour
</code></pre>