DiskCache

5.6.3.post1 · active · verified Thu Apr 16

DiskCache is a pure-Python, thread-safe, and process-safe disk-backed persistent cache. It supports various data types, cache eviction policies, and can be used in web servers, for caching slow function results, and in batch jobs. The library is actively maintained with regular updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a DiskCache instance, store and retrieve data, and clean up the cache directory. It uses a context manager (`with Cache(...)`) for proper cache management and shows basic `set` and `get` operations. A `size_limit` is included as a best practice.

from diskcache import Cache
import os

# Create a cache in a specified directory
# It's good practice to manage cache directories, e.g., in a temp folder or user data dir.
cache_dir = os.path.join(os.getcwd(), 'my_app_cache')

# Use a context manager to ensure the cache is properly closed
with Cache(cache_dir, size_limit=1e9) as cache:
    # Set a key-value pair
    cache.set('greeting', 'Hello, DiskCache!')

    # Get a value by key
    value = cache.get('greeting')
    print(f"Retrieved value: {value}")

    # Check if a key exists
    if 'another_key' not in cache:
        cache.set('another_key', 123)
    print(f"Another key's value: {cache.get('another_key')}")

# The cache persists after the 'with' block, and can be reopened.
with Cache(cache_dir) as cache:
    print(f"Reopened cache value: {cache.get('greeting')}")

# Clean up the cache directory for repeated runs in examples
# In a real application, you would manage its lifecycle.
import shutil
if os.path.exists(cache_dir):
    shutil.rmtree(cache_dir)

view raw JSON →