Caching in Python with Examples

In this tutorial, you will learn about how to cache frequently needed data in Python for making the code faster.

Caching is a programming technique to store frequently required data in a temporary location for faster access rather than requesting it from the main source every time.

Every Python programmer should be familiar with the concept of caching. In this tutorial, we will learn how to implement caching in a Python program using the cachetools Python library. cachetools includes a number of classes that implement caches using various cache algorithms derived from Cache class which, in turn, is derived from the collections.MutableMapping.

Caching Each Data for a Specified Time

TTLCache is an implementation of LRU cache with a per-item time-to-live (TTL) value. Each cached item has a time-to-live value and the item will no longer be accessible after the time-to-live value expires.

from cachetools import TTLCache
from datetime import datetime, timedelta

#Creating cache where each item will be accessbile for 1 hour
cache_data = TTLCache(maxsize=50000, ttl=timedelta(hours=1),

data_item1 = ""
data_item2 = ""
data_item3 = ""
data_item4 = ""
data_item5 = ""

#Storing data in cache
cache_data[hash(data_item1)] = data_item1
cache_data[hash(data_item2)] = data_item2
cache_data[hash(data_item3)] = data_item3
cache_data[hash(data_item4)] = data_item4
cache_data[hash(data_item5)] = data_item5

#Accessing data from cache
item = cache_data.get(hash(data_item2), None)

print("Getting from cache = ", item)

The output of the above example will look like this:

Getting from cache =