擅长:python、mysql、java
<p>OP使用的是Python2.7,但如果您使用的是Python3,则接受的答案中提到的<code>ExpiringDict</code>目前已经过期。对<a href="https://github.com/mailgun/expiringdict" rel="noreferrer">github repo</a>的最后一次提交是2017年6月17日,有一个公开的问题是它<a href="https://github.com/mailgun/expiringdict/issues/16" rel="noreferrer">doesn't work with Python 3.5</a></p>
<p>有一个最近维护的项目<a href="https://github.com/tkem/cachetools" rel="noreferrer">cachetools</a>(上次提交时间:2018年6月14日)</p>
<p><code>pip install cachetools</code></p>
<pre><code>from cachetools import TTLCache
cache = TTLCache(maxsize=10, ttl=360)
cache['apple'] = 'top dog'
...
>>> cache['apple']
'top dog'
... after 360 seconds...
>>> cache['apple']
KeyError exception thrown
</code></pre>
<p><code>ttl</code>是以秒为单位的生存时间。</p>