Recipe 3.6 · Python
A Typed Cache Wrapper
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
Problem
After a few years, cache keys are string literals scattered through the code, each call site picks its own lifetime, and the value type is whatever the caller casts it to. Nobody can answer the questions that matter: what is cached, for how long, and what invalidates it.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Cache keys, types and lifetimes decided at each call site
Source: ImproveCode, Chapter 3, Recipe 3.6 "A Typed Cache Wrapper"
Section: The way it's often written
Book page: 74 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
CacheManager -> an untyped static helper over a dict; the "as CustomerProfile" cast -> isinstance.
"""
from typing import Any
class CustomerProfile:
pass
class CacheManager:
_items: dict[str, Any] = {}
@staticmethod
def get(key: str) -> Any:
return CacheManager._items.get(key)
@staticmethod
def add(key: str, value: Any, duration: int) -> None:
CacheManager._items[key] = value
@staticmethod
def remove(key: str) -> None:
CacheManager._items.pop(key, None)
def usage(repo: Any, id: int) -> CustomerProfile | None:
# Not to copy: keys, types and lifetimes decided at each call.
profile = CacheManager.get("Cust" + str(id))
if not isinstance(profile, CustomerProfile):
profile = repo.load_profile(id)
CacheManager.add("Cust" + str(id), profile, 20) # minutes? seconds?
# Elsewhere, years later:
CacheManager.remove("Customer_" + str(id)) # a different key
return profile
The improved recipe
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Typed cache keys with a wrapper and a no-op cache for tests
Source: ImproveCode, Chapter 3, Recipe 3.6 "A Typed Cache Wrapper"
Section: The improved recipe
Book page: 74-75 -- original C# listing
Converted from C# to Python.
CacheKey<T> -> generic frozen dataclass CacheKey[T] (type checkers tie key to value type);
IAppCache -> Protocol; SingleFlightCache comes from the Recipe 3.4 file.
"""
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from datetime import timedelta
from decimal import Decimal
from typing import Protocol
from p068_r3_4_single_flight_cache import SingleFlightCache
@dataclass(frozen=True)
class CacheKey[T]:
name: str
time_to_live: timedelta
def __str__(self) -> str:
return self.name
@dataclass(frozen=True)
class CustomerProfile:
customer_id: int
display_name: str
tier: str
@dataclass(frozen=True)
class TaxRate:
region: str
rate: Decimal
class CacheKeys:
@staticmethod
def customer(id: int) -> CacheKey[CustomerProfile | None]:
return CacheKey(f"customer:v1:{id}", timedelta(minutes=20))
TAX_RATES: CacheKey[list[TaxRate]] = CacheKey("taxrates:v1", timedelta(hours=12))
class AppCache(Protocol):
async def get_or_create[T](self, key: CacheKey[T],
factory: Callable[[], Awaitable[T]]) -> T: ...
def remove[T](self, key: CacheKey[T]) -> None: ...
class AppMemoryCache:
def __init__(self, cache: SingleFlightCache) -> None:
self._cache = cache
async def get_or_create[T](self, key: CacheKey[T],
factory: Callable[[], Awaitable[T]]) -> T:
return await self._cache.get_or_create(key.name, factory, key.time_to_live)
def remove[T](self, key: CacheKey[T]) -> None:
self._cache.remove(key.name)
# For unit tests: always calls the factory, caches nothing.
class NoCache:
async def get_or_create[T](self, key: CacheKey[T],
factory: Callable[[], Awaitable[T]]) -> T:
return await factory()
def remove[T](self, key: CacheKey[T]) -> None:
pass
How it works
CacheKey<T> ties three facts together: the key string, the type stored under it, and how long it lives. Every key the application uses is defined once, in CacheKeys. The compiler now does the checking that used to happen at run time. GetOrCreateAsync(CacheKeys.Customer(id), ...) can only take a factory that returns a CustomerProfile?, and the result needs no cast.
Call sites become short and uniform:
The reader and the writer both build the key through CacheKeys.Customer, so they cannot drift apart the way "Cust" and "Customer_" did. The v1 in each key gives you a versioning switch for when the cached type changes shape.
AppMemoryCache delegates to the SingleFlightCache from Recipe 3.4, so every typed entry gets stampede protection for free. Register both as singletons, with IAppCache mapped to AppMemoryCache. In unit tests, register NoCache instead and the code under test always reaches its repository, which keeps tests honest and independent of each other.
CacheKeys doubles as documentation. When someone asks what the application caches, the answer is one file, with every lifetime written next to its key.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Using a typed cache key to load and invalidate a customer profile
Source: ImproveCode, Chapter 3, Recipe 3.6 "A Typed Cache Wrapper"
Section: How it works
Book page: 75 -- original C# listing
Converted from C# to Python.
Usage fragment wrapped in async functions; the token-taking lambda becomes a zero-argument
lambda since asyncio cancellation replaces CancellationToken.
"""
from typing import Protocol
from p074_r3_6_typed_cache_key_wrapper import AppCache, CacheKeys, CustomerProfile
class ProfileRepository(Protocol):
async def find(self, customer_id: int) -> CustomerProfile | None: ...
async def load_profile(app_cache: AppCache, profiles: ProfileRepository,
customer_id: int) -> CustomerProfile | None:
# Usage snippet
profile = await app_cache.get_or_create(
CacheKeys.customer(customer_id),
lambda: profiles.find(customer_id))
return profile
def after_profile_saved(app_cache: AppCache, customer_id: int) -> None:
# After saving a profile change:
app_cache.remove(CacheKeys.customer(customer_id))
Variations and pitfalls
- A distributed implementation of
IAppCacheis a few lines overJsonDistributedCachefrom Recipe 3.5. Because callers depend on the interface, you can move from memory to Redis without touching them. Note thatRemovewould then need to be async; if you expect that move, define the interface withRemoveAsyncfrom the start. - Keep
CacheKeyssmall. If it grows past a few dozen entries, split it by feature (CustomerCacheKeys,PricingCacheKeys), but keep each key's lifetime next to its name. - Do not let the wrapper grow into a framework. Tags, regions and dependency graphs between entries are where homegrown cache managers go to become unmaintainable. Keep the wrapper this size and use
HybridCacheif you need more. - Normalize key parts. Build keys from invariant, normalized values:
ToUpperInvariant()for codes,CultureInfo.InvariantCulturefor numbers and dates."customer:v1:42"must be the same string on every server.