此模块提供了各种 memoizing 集合和装饰器, 包括 Python 标准库的 @lru_cache 函数装饰器的变体。
from cachetools import cached, LRUCache, TTLCache
# 使用动态规划加速斐波那契数的计算
@cached(cache={})
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
# 缓存最近最少使用的 Python Enhancement Proposals
@cached(cache=LRUCache(maxsize=32))
def get_pep(num):
url = 'http://www.python.org/dev/peps/pep-%04d/' % num
with urllib.request.urlopen(url) as s:
return s.read()
# 缓存天气数据,时效不超过十分钟
@cached(cache=TTLCache(maxsize=1024, ttl=600))
def get_weather(place):
return owm.weather_at_place(place).get_weather()在此模块的上下文中,缓存 是一个 固定最大尺寸的 可变 映射。 当缓存已满,即添加另一项会超出其最大尺寸时,缓存必须根据合适的 缓存算法 来选择要丢弃的项。
此模块提供了基于不同缓存算法的多个缓存类,以及用于轻松 memoization 函数和 方法调用的装饰器。
cachetools 可从 PyPI 获取,可以通过运行以下命令安装:
pip install cachetools
此包的类型存根由 typeshed 提供,可以通过运行以下命令安装:
pip install types-cachetools
- asyncache: 用于与 asyncio 一起使用 cachetools 的助手。
- cachetools-async: 用于与 asyncio 一起使用 cachetools 的助手。
- cacheing: Pure Python Cacheing Library。
- CacheToolsUtils: 可堆叠的缓存类,用于在 cachetools、redis 和 memcached 之上实现共享、加密、 统计 等功能。
- shelved-cache: Python cachetools 的持久化缓存实现。
Copyright (c) 2014-2026 Thomas Kemmer。
根据 MIT 许可证 授权。