python - 如何解决从 LRU 缓存打印值并在一段时间后删除值时遇到的问题?

标签 python caching ttl lru

我一直在尝试实现我自己的 LRU 缓存版本,该版本会在短时间内删除最近最少使用的值。我正在使用在 ( https://www.kunxi.org/blog/2014/05/lru-cache-in-python/ ) 中找到的代码作为模板。

(这是在那里找到的代码,因此您不必打开它):

class LRUCache:
    def __init__(self, capacity):
        self.capacity = capacity
        self.tm = 0
        self.cache = {}
        self.lru = {}

    def get(self, key):
        if key in self.cache:
            self.lru[key] = self.tm
            self.tm += 1
            return self.cache[key]
        return -1

    def set(self, key, value):
        if len(self.cache) >= self.capacity:
            # find the LRU entry
            old_key = min(self.lru.keys(), key=lambda k:self.lru[k])
            self.cache.pop(old_key)
            self.lru.pop(old_key)
        self.cache[key] = value
        self.lru[key] = self.tm
        self.tm += 1

这段代码按预期工作

cache = LRUCache(2)
cache.set(1, 20)
cache.set(2, 40)

print(cache.get(2))
40

但对于这种情况,它返回一个错误:

for i in cache:
    print(i)

Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'LRUCache' object is not iterable

我期望的输出是:

(1, 20)
(2, 40)

为什么它不适用于这种情况以及如何让它打印我的预期输出?

另外,我想自动删除长时间在缓存中的值,我已经尝试过,但无法完成此操作。我尝试修改代码:

from time import time

class LRUCache:
    def __init__(self, capacity, expiry_time):
        self.capacity = capacity
        self.expiry_time = expiry_time
        self.expired = False
        self.tm = 0
        self.cache = {}
        self.lru = {}

    def get(self, key):
        if key in self.cache:
            self.lru[key] = self.tm
            self.tm += 1
            return self.cache[key]
        return -1
        if self.expired is False:
            return (self.expires_at < time())
        if self.expires_at < time():
            return -1


    def set(self, key, value):
        if len(self.cache) >= self.capacity:
            # find the LRU entry
            old_key = min(self.lru.keys(), key=lambda k:self.lru[k])
            self.cache.pop(old_key)
            self.lru.pop(old_key)
        self.cache[key] = value
        self.lru[key] = self.tm
        self.tm += 1

但是,即使进行了更改,当我尝试“获取”值时,它们在超过到期时间时也不会返回 -1。我该如何解决这个问题?

最佳答案

为什么它不适用于这种情况以及如何让它打印我的预期输出?

您的缓存对象收到错误对象不可迭代,因为您尚未实现任何使其可迭代的方法。

这也许最好留给另一个问题:Build a Basic Python Iterator

引用 this answer :

There are four ways to build an iterative function:

  • ...
  • ...
  • create an iterator (defines __iter__ and __next__ (or next in Python 2.x))
  • create a function that Python can iterate over on its own (defines __getitem__)

根据我的更改,当我尝试“获取”值时,它们在超过到期时间后不会返回 -1

对于您的更改,您已将它们放在函数的末尾,因此默认功能始终首先发生。这需要重新排列:

class LRUCache:
    def __init__(self, capacity, expiry_time):
        ...

    def get(self, key):
        if self.expired is False:
            return (self.expires_at < time())
        if self.expires_at < time():
            return -1
        if key in self.cache:
            self.lru[key] = self.tm
            self.tm += 1
            return self.cache[key]
        return -1

    def set(self, key, value):
        ...

但是,实现过程中还存在一些其他直接问题:

  • self.expiry_time 一旦设置就不会被使用或检查。
  • self.expires_at 从未定义。
  • if self.expired is False:这将始终报告True,因为expired永远不会改变。
    • 并且(一旦定义了 expires_at)将仅返回 True

关于python - 如何解决从 LRU 缓存打印值并在一段时间后删除值时遇到的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47794255/

相关文章:

ios - 如何从 RESTful API 获取所有数据?

java - AzureDocumentDB MongoDB协议(protocol)支持: Failing to create TTL index

python - 测试经过身份验证的 django-rest-framework 路由时出现 405 错误

python - 如何用 df.loc 或 df.iloc 替换 df.ix?

通过表进行 HTTP 缓存 最近修改时间

javascript - 将 React 类组件中的 setState 传递给外部函数时出错?

c - 如何在没有 root 权限的情况下从 Linux 上的 C 中的 UDP 数据包中取回超过 TTL 的错误消息?

cassandra - cassandra 中 TTL 的最大值

python - 将数组写入 csv python(一列)

python - 队列空方法坏了吗?