要在 Python 中使用缓存,你可以使用 functools
模块中的 lru_cache
装饰器。这个装饰器可以自动在函数调用中使用缓存,并且可以指定缓存的大小。
下面是一个例子,展示了如何在读写文件的函数中使用 lru_cache
装饰器:
from functools import lru_cache
@lru_cache(maxsize=32)
def read_file(file_name):
with open(file_name, 'r') as f:
return f.read()
@lru_cache(maxsize=32)
def write_file(file_name, data):
with open(file_name, 'w') as f:
f.write(data)
在上面的代码中,我们使用了 lru_cache
装饰器来修饰 read_file
和 write_file
函数。我们还指定了缓存的大小为 32。这意味着,函数的调用结果会被缓存在最多 32 个条目的字典中。当缓存满了,最少使用的条目会被淘汰。
注意,在使用 lru_cache
装饰器时,你需要确保函数的返回值是可哈希的。否则,装饰器会抛出一个 TypeError
异常。