Lab 09: JIT & Caching Patterns

Time: 60 minutes | Level: Architect | Docker: docker run -it --rm python:3.11-slim bash

Overview

Python's functools.cache and lru_cache are implemented in C for maximum performance. This lab explores their internals, builds a TTL-aware cache decorator, and covers disk-backed memoization patterns for production workloads.

Step 1: functools.lru_cache Internals

import functools
import sys

@functools.lru_cache(maxsize=128)
def fib(n: int) -> int:
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

# Compute and inspect cache
result = fib(30)
print(f"fib(30) = {result}")

info = fib.cache_info()
print(f"Cache info:")
print(f"  hits={info.hits}, misses={info.misses}")
print(f"  maxsize={info.maxsize}, currsize={info.currsize}")
print(f"  hit rate: {info.hits/(info.hits+info.misses)*100:.1f}%")

# __wrapped__ gives access to the unwrapped function
unwrapped = fib.__wrapped__
print(f"\nfib.__wrapped__ is fib: {unwrapped is fib}")
print(f"fib.__wrapped__(5) = {unwrapped(5)}")  # No caching, recursive call

# Clear and recompute
fib.cache_clear()
info_after = fib.cache_info()
print(f"\nAfter cache_clear: {info_after}")

📸 Verified Output:

💡 lru_cache uses a doubly-linked list + dict for O(1) get/set. The C implementation (_functools) is ~10x faster than a pure Python equivalent.

Step 2: functools.cache — Unbounded Cache

Step 3: Understanding Cache Key Generation

Step 4: Custom TTL Cache Decorator

📸 Verified Output:

Step 5: Method Caching with cached_property

Step 6: Memoization with Disk Cache (joblib pattern)

Step 7: Caching with numpy — Ufunc Caching

Step 8: Capstone — Production Cache Layer

Summary

Concept
API
Use Case

LRU cache

functools.lru_cache

Expensive pure functions

Unbounded cache

functools.cache

Small result spaces

Cache introspection

.cache_info(), .__wrapped__

Debug and monitor

TTL cache

Custom decorator

Time-sensitive data

cached_property

functools.cached_property

Expensive computed attributes

Disk cache

Custom + pickle

ML/large computation persistence

Array cache

Custom key from tobytes()

numpy operations

Production cache

Thread-safe LRU+TTL

Microservice caching layer

Last updated