Typing stubs for cachetools

6.2.0.20260317 · active · verified Sun Mar 29

types-cachetools provides static type annotations for the cachetools library, enabling type checkers like MyPy and Pyright to validate code that utilizes caching mechanisms. The current version, 6.2.0.20260317, aims to provide accurate annotations for cachetools versions 6.2.*. It is part of the typeshed project, which collects high-quality type stubs for various Python packages.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic usage of `cachetools` decorators like `@cached` with `LRUCache` and `TTLCache`. With `types-cachetools` installed, type checkers will provide static analysis for these caching patterns, helping to ensure correct usage of cache parameters and function signatures.

from cachetools import cached, LRUCache, TTLCache
import time

# Example 1: LRUCache decorator
@cached(cache=LRUCache(maxsize=2))
def expensive_function(arg):
    print(f"Calculating expensive_function({arg})")
    time.sleep(0.1) # Simulate work
    return arg * 2

print("--- LRUCache Example ---")
print(expensive_function(1)) # Calculates
print(expensive_function(2)) # Calculates
print(expensive_function(1)) # Cache hit
print(expensive_function(3)) # Calculates, evicts 2
print(expensive_function(2)) # Calculates again

# Example 2: TTLCache decorator
@cached(cache=TTLCache(maxsize=1, ttl=0.5))
def time_sensitive_data(key):
    print(f"Fetching time_sensitive_data({key})")
    return f"Data for {key} @ {time.time():.2f}"

print("\n--- TTLCache Example ---")
print(time_sensitive_data("report")) # Calculates
print(time_sensitive_data("report")) # Cache hit
time.sleep(0.6) # Wait for cache to expire
print(time_sensitive_data("report")) # Calculates again

view raw JSON →