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。我该如何解决?

最佳答案

为什么在这种情况下不起作用,如何获得它以打印预期的输出?

您的cache对象收到错误object is not iterable,因为您尚未实现使其可迭代的任何方式。

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

引用this answer


  有四种方法来构建迭代函数:
  
  
  ...
  ...
  创建一个迭代器(定义__iter____next__(或Python 2.x中的next))
  创建一个Python可以自己迭代的函数(定义__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/

相关文章:

python - 将XML文档导入Django的(postgres)数据库

javascript - 延迟加载Javascript,不是从IE8缓存创建的对象

c++ - 计算缓存命中率和未命中率的程序

Redis ttl payload 内存大小

python - 如何在Windows中的多行字符串中使用换行符来打印新行?

python - 将多行分配给 Pandas 中的一个索引

MongoDB 索引在更新时增长

javascript - 是否有一种标准方法可以在特定时间使用 Meteor 和 moment.js 从集合中删除 Mongo 文档?

python - 如何用Python选择网页的特定表格

asp.net - HttpRuntime缓存和HttpContext缓存之间有什么区别?