Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Cache expensive function with lru_cache in Python
Use functools.lru_cache to memoize an expensive recursive function and show the dramatic speedup on repeated calls.
from functools import lru_cache
import time
@lru_cache(maxsize=128)
def expensive_operation(n):
"""Simulate an expensive Fibonacci-like calculation."""
if n < 2:
return n
return expensive_operation(n - 1) + expensive_operation(n - 2)
if __name__ == "__main__":
# First call (uncached) - take…
How to Implement Memoized Fibonacci in Python with functools.cache
Use functools.cache to memoize a recursive Fibonacci function, avoiding repeated computation and dramatically speeding up the calculation.
from functools import cache
@cache
def fibonacci(n: int) -> int:
"""Return the n-th Fibonacci number (0-indexed)."""
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
if __name__ == "__main__":
for i in range(10):
print(f"fibonacci({i}) = {fibonacci(i)}")
print(f"Cache…
How to Invalidate Cache When Arguments Change in Python
A memoization decorator that caches function results keyed by arguments, automatically invalidating when inputs change.
from functools import wraps
def memoize(func):
cache = {}
@wraps(func)
def wrapper(*args, **kwargs):
key = (args, tuple(sorted(kwargs.items())))
if key not in cache:
cache[key] = func(*args, **kwargs)
return cache[key]
return wrapper
@memoize
def expensiv…
How to Build a TTL Cache Dict in Python
Create a dictionary subclass that automatically expires keys after a fixed time-to-live using timestamps.
import time
class TTLDict(dict):
def __init__(self, ttl, *args, **kwargs):
self.ttl = ttl
self._expires = {}
super().__init__(*args, **kwargs)
def __setitem__(self, key, value):
super().__setitem__(key, value)
self._expires[key] = time.time() + self.ttl
def __geti…
LRU Cache with OrderedDict in Python
Implement an LRU cache using collections.OrderedDict to track insertion order and evict the least-recently-used item when capacity is exceeded.
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.cache = OrderedDict()
def get(self, key):
if key not in self.cache:
return -1
self.cache.move_to_end(key)
return self.cache[key]
def put(sel…
Cache LLM Completions by Hashing the Prompt in Python
A simple in-memory cache that stores LLM completions keyed by a SHA-256 hash of the prompt to avoid recomputing identical requests.
import hashlib
import json
class PromptCache:
def __init__(self):
self.cache = {}
def _hash_prompt(self, prompt: str) -> str:
return hashlib.sha256(prompt.encode("utf-8")).hexdigest()
def get(self, prompt: str) -> str | None:
key = self._hash_prompt(prompt)
return self.ca…
How to Build a Simple Semantic Cache for Similar Prompts in Python
Mock a semantic cache that finds the closest matching prompt using word-overlap similarity and returns cached results above a threshold.
prompt_cache = [
"What is the capital of France?",
"How does recursion work?",
"Best practices for Python logging?",
"Explain binary search in one line.",
"How to reverse a string in Python?"
]
def normalize(text):
return " ".join(text.lower().split())
def similarity(a, b):
a_words = set(…
How to cache embeddings with a Python dict to avoid recomputation
Caches embeddings computed from text in a dictionary keyed by SHA-256 hash, returning cached results for repeated calls.
import hashlib
import time
class EmbeddingCache:
def __init__(self):
self.cache = {}
def _hash_text(self, text):
return hashlib.sha256(text.encode()).hexdigest()
def get_embedding(self, text, compute_func):
key = self._hash_text(text)
if key not in self.cache:
…
How to Archive a Repository as a ZIP in Python
Create a ZIP archive of a repository directory with a mock export, skipping hidden files and __pycache__ folders.
import zipfile
import io
import os
from pathlib import Path
def archive_repo_mock(repo_path, output_path="repo_archive.zip"):
"""Create a zip archive of a repository directory (mock export)."""
repo = Path(repo_path)
if not repo.exists():
raise FileNotFoundError(f"Repository not found: {repo}")
…
How to Memoize Async Functions with lru_cache in Python
Cache async function results with functools.lru_cache to avoid repeated expensive awaits, cutting total execution from ~0.4s to ~0.2s in this example.
from functools import lru_cache
import asyncio
@lru_cache(maxsize=128)
async def fetch_data(user_id: int) -> str:
# Simulate expensive async operation
await asyncio.sleep(0.1)
return f"Data for user {user_id}"
async def main():
start = asyncio.get_event_loop().time()
# First calls (miss cach…
How to Memoize Pure Functions with functools.lru_cache in Python
Use functools.lru_cache to memoize a pure Fibonacci function and avoid recomputing repeated values.
from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n: int) -> int:
"""Return the nth Fibonacci number (0-indexed) using memoization."""
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
if __name__ == "__main__":
for i in range(10):
print(f"fibonacci({…
How to Use a Weakref Cache to Avoid Memory Leaks in Python
This code demonstrates building a value cache with weakref.WeakValueDictionary so objects can be garbage collected when no longer referenced, preventing memory leaks.
import weakref
import gc
class ExpensiveObject:
def __init__(self, name):
self.name = name
def __repr__(self):
return f"ExpensiveObject('{self.name}')"
class ObjectCache:
def __init__(self):
self._cache = weakref.WeakValueDictionary()
def get_or_create(self, name):
…
How to Use functools.cache for Unbounded Memoization in Python
Speed up repeated recursive calls by memoizing function results with Python's built-in functools.cache decorator.
```python
import functools
import time
@functools.cache
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
if __name__ == "__main__":
start = time.perf_counter()
result = fib(30)
elapsed = time.perf_counter() - start
print(f"fib(30) = {result}")
print(f"computed in {…
How to implement stale-while-revalidate caching in Python
A Python cache wrapper that returns a stale cached value with a fallback flag when the upstream fetch fails, using TTL-based freshness checks.
import time
from functools import lru_cache
class CachedService:
def __init__(self, fetch_func, ttl=5):
self.fetch_func = fetch_func
self.ttl = ttl
self._cache = {}
self._timestamp = {}
def get(self, key):
now = time.time()
if key in self._cache and now - self…
Lazy loading with a proxy in Python: defer expensive service creation
A lazy proxy defers creating an expensive service object until its method is first called, then caches it for reuse.
import time
import random
class ExpensiveService:
def __init__(self, name):
self.name = name
print(f"Creating expensive service: {self.name}")
def fetch_data(self):
time.sleep(1)
return f"Data from {self.name}: {random.randint(1, 100)}"
class LazyProxy:
def __init__(sel…
How to Mock HTTP 304 Responses with If-None-Match in Python
Spin up a local HTTP server that returns a 304 Not Modified when a request carries a matching ETag, useful for testing cache behavior.
from http.server import BaseHTTPRequestHandler, HTTPServer
from threading import Thread
import urllib.request
ETAG = '"abc123"'
BODY = b'{"status": "ok"}'
class MockServer(BaseHTTPRequestHandler):
def do_GET(self):
if self.headers.get('If-None-Match') == ETAG:
self.send_response(304)
…
Cache Asides in Python with a Read-Through Loader
Implements a cache-aside pattern with a read-through loader that fetches missing keys from a backing data store and caches them.
class DataStore:
"""Mock database with a few records."""
def __init__(self):
self.data = {1: "Alice", 2: "Bob", 3: "Charlie"}
def get(self, key):
print(f"Loading key {key} from database")
return self.data.get(key)
class CacheAsideLoader:
"""Cache-aside pattern with a read-thr…
Cache Data in Redis with Python
A beginner-friendly Redis cache helper that stores JSON strings with a TTL and retrieves them with the redis-py client.
import redis
class DataCache:
def __init__(self, host="localhost", port=6379, db=0):
self.client = redis.Redis(host=host, port=port, db=db, decode_responses=True)
def cache_data(self, key, value, ttl=60):
self.client.setex(key, ttl, value)
def get_cached_data(self, key):
return …
Cache Penetration Null Object Mock in Python
Implement a cache that stores a null marker on misses to prevent repeated database hits, reducing cache penetration.
import time
from collections import defaultdict
from typing import Any, Optional
class Cache:
def __init__(self):
self.store: dict[str, Any] = {}
self.ttl: dict[str, float] = {}
self.null_marker = object()
def get(self, key: str, ttl: int = 60, fallback:
Any = None) -> An…
Cache Stampede Prevention with SingleFlight in Python
Implements a SingleFlight pattern in Python to deduplicate concurrent cache-miss computations and prevent cache stampede.
import threading
import time
from functools import wraps
class SingleFlight:
def __init__(self):
self._lock = threading.Lock()
self._inflight = None
def do(self, key, fn):
with self._lock:
if self._inflight is not None:
return self._inflight[1]
…
Cache Warming with Python: Preload Hot Keys
Demonstrates a simple LRU-like cache with a warm method that preloads hot keys with mock values using OrderedDict.
import time
from collections import OrderedDict
class CacheWarm:
def __init__(self, capacity=3):
self.capacity = capacity
self.cache = OrderedDict()
self.hot_keys = []
def warm(self, keys):
"""Preload hot keys into cache with mock values."""
for key in keys:
…
Consistent Hashing Cache Shard in Python
A minimal consistent hashing ring with virtual nodes that distributes cache keys across shards and minimizes re-mapping when a node is removed.
import hashlib
import bisect
class ConsistentHashRing:
def __init__(self, nodes=None, replicas=3):
self.replicas = replicas
self.ring = {}
self.sorted_keys = []
if nodes:
for node in nodes:
self.add_node(node)
def _hash(self, key):
return i…
How to Add TTL Jitter to Cache Expiration in Python
A Python decorator that adds random jitter to cache TTLs, staggering expiration times to prevent cache avalanche.
import random
import time
from functools import wraps
def add_jitter(ttl: float, jitter_range: float = 0.1) -> float:
"""Add random jitter (as % of TTL) to stagger cache expiration and prevent avalanche."""
jitter = random.uniform(-jitter_range, jitter_range)
return ttl * (1 + jitter)
def cache_with_jitt…
How to Build a Bloom Filter to Reduce Cache Misses in Python
Implement a probabilistic Bloom filter in Python that lets a cache quickly determine which keys are definitely not present, reducing expensive source lookups on cache misses.
import hashlib
import random
class BloomFilter:
def __init__(self, size=100, num_hashes=3):
self.size = size
self.num_hashes = num_hashes
self.bit_array = [0] * size
def _hashes(self, item):
result = []
for i in range(self.num_hashes):
hash_value = int(hash…
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.