This module provides various memoizing collections and decorators, including variants of the Python Standard Library's @lru_cache function decorator.
from cachetools import cached, LRUCache, TTLCache
# speed up calculating Fibonacci numbers with dynamic programming
@cached(cache={})
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
# cache least recently used 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()
# cache weather data for no longer than ten minutes
@cached(cache=TTLCache(maxsize=1024, ttl=600))
def get_weather(place):
return owm.weather_at_place(place).get_weather()
For the purpose of this module, a cache is a mutable mapping of a
fixed maximum size. When the cache is full, i.e. by adding another
item the cache would exceed its maximum size, the cache must choose
which item(s) to discard based on a suitable cache algorithm. In
general, a cache's size is the total size of its items, and an item's
size is a property or function of its value, e.g. the result of
sys.getsizeof(value)
. For the trivial but common case that each
item counts as 1
, a cache's size is equal to the number of its
items, or len(cache)
.
Multiple cache classes based on different caching algorithms are implemented, and decorators for easily memoizing function and method calls are provided, too.
cachetools is available from PyPI and can be installed by running:
pip install cachetools
Copyright (c) 2014-2020 Thomas Kemmer.
Licensed under the MIT License.