Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Mock a Redis Transaction with MULTI/EXEC in Python
A minimal in-memory mock of Redis MULTI/EXEC transactions that queues commands and applies them atomically on EXEC.
class RedisTransactionMock:
def __init__(self):
self.data = {}
self.queue = []
self.in_transaction = False
def multi(self):
self.in_transaction = True
self.queue = []
return "OK"
def set(self, key, value):
if self.in_transaction:
self.qu…
How to Mock zlib Compression for Cache Values in Python
Compress cache values with zlib and mock the compress function in unit tests to simulate cache behavior.
import zlib
from unittest.mock import patch
def compress_value(data: bytes) -> bytes:
"""Compress data using zlib and return the compressed bytes."""
return zlib.compress(data)
def decompress_value(compressed: bytes) -> bytes:
"""Decompress zlib data and return the original bytes."""
return zlib.deco…
How to Serialize Cache Values with JSON and Pickle in Python
Serialize cache values using JSON for simple types or pickle for arbitrary objects, with robust error handling for unsupported types like mocks.
import json
import pickle
from unittest.mock import Mock
def serialize(value, method="json"):
"""Serialize a cache value using JSON or pickle with type checking."""
if method == "json":
try:
return json.dumps(value).encode("utf-8")
except TypeError as e:
raise ValueErro…
How to Use Redis HSET and HGET in Python
This code demonstrates how to store and retrieve hash data in Redis using Python's redis library with HSET, HGET, HGETALL, and HDEL commands.
import redis
# Connect to Redis (adjust host/port as needed)
r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
# Clear any existing data for demonstration
r.delete('user:1')
# HSET - Store a hash
r.hset('user:1', mapping={'name': 'Alice', 'age': 30, 'city': 'New York'})
# HGET - Retrieve a …
How to Use Redis ZADD and ZRANGE in Python
Add members to a Redis sorted set with ZADD and retrieve them in score order with ZRANGE in Python.
import redis
client = redis.Redis(host='localhost', port=6379, db=0)
client.delete('scores')
members = {'alice': 30, 'bob': 20, 'carol': 50}
for name, score in members.items():
client.zadd('scores', {name: score})
result = client.zrange('scores', 0, -1)
print(result)
How to Use lru_cache in Python for Cache-on-Miss Population
Demonstrates lru_cache to automatically populate cache on a miss and serve subsequent calls from cache, with cache info stats.
from functools import lru_cache
@lru_cache(maxsize=None)
def fetch_user(user_id):
"""Simulates a slow database fetch."""
print(f"Cache miss: fetching user {user_id} from database")
return {"id": user_id, "name": f"User {user_id}"}
if __name__ == "__main__":
user = fetch_user(1)
print(f"First call…
How to Validate and Cache Data with Redis in Python
A beginner-friendly helper that validates email, phone, and age data and caches validated entries in Redis for 5 minutes.
import redis
import json
from functools import wraps
class DataValidator:
def __init__(self, host="localhost", port=6379, db=0):
self.cache = redis.Redis(host=host, port=port, db=db)
self.validators = {
"email": lambda v: "@" in v and "." in v.split("@")[-1],
"phone": lambd…
How to cache filtered data in Redis with Python
This code caches filtered list results in Redis using an MD5 hash key, returning cached results when available.
import redis
import json
import hashlib
import time
cache = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
def filter_data(data, predicate_key, predicate_value):
"""Filter a list of dicts by key-value pair, with Redis caching."""
cache_key = hashlib.md5(
f"{predicate_key}:{pred…
How to create a stable cache key from function arguments in Python
Generate a stable SHA-256 cache key from normalized function arguments, with keyword order normalized and tests using mocks.
import hashlib
import json
from unittest.mock import Mock
def make_cache_key(*args, **kwargs):
"""Normalize args/kwargs into a stable hash key for caching."""
normalized = {
"args": [repr(arg) for arg in args],
"kwargs": {key: repr(value) for key, value in sorted(kwargs.items())}
}
pa…
How to implement a token bucket rate limiter in Python
A thread-safe in-memory token bucket rate limiter that tracks per-key tokens with refill logic, including a usage example after a timed refill.
import time
import threading
class TokenBucketRateLimiter:
def __init__(self, capacity, refill_rate):
self.capacity = capacity
self.refill_rate = refill_rate
self.tokens = capacity
self.last_refill_time = time.time()
self.lock = threading.Lock()
def allow_request(self,…
How to memoize a function in Python with lru_cache
Use functools.lru_cache to memoize a recursive Fibonacci function, caching results for a fixed number of calls to avoid repeated computation.
from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
if __name__ == "__main__":
for i in range(10):
print(f"fib({i}) = {fibonacci(i)}")
print(f"Cache info: {fibonacci.cache_info()}")
How to use Redis MGET MSET pipeline in Python
Store multiple keys atomically and read them efficiently with Redis MSET/MGET, then batch commands with a pipeline to cut round trips.
import redis # v4.x+ required
r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)
# Sample data to store
r.flushdb()
data = {"name": "Alice", "age": "30", "city": "Berlin"}
# MSET: store multiple key-value pairs in one command
r.mset(data)
# MGET: fetch multiple keys in one round trip
keys =…
Redis Cache Helper Class in Python with TTL
Build a DataHelper class that caches function results in Redis with a default TTL, using get_or_set and clear methods.
import redis
import json
import time
class DataHelper:
def __init__(self, host="localhost", port=6379, db=0, default_ttl=60):
self.client = redis.Redis(host=host, port=port, db=db, decode_responses=True)
self.default_ttl = default_ttl
def get_or_set(self, key, data_func, ttl=None):
c…
Redis GET SET EX TTL mock in Python
A thread-safe Python class mimicking Redis GET, SET with EX, and TTL commands for in-memory testing.
import time
import threading
from typing import Optional, Callable
class RedisTTLMock:
def __init__(self):
self._store: dict[str, tuple[str, float]] = {}
self._lock = threading.Lock()
def set(self, key: str, value: str, ex: Optional[int] = None) -> bool:
expiry = time.time() + ex if …
Redis SADD SMEMBERS Set Mock in Python
A lightweight mock of Redis SADD and SMEMBERS using Python sets for testing or local caching.
class RedisSetMock:
def __init__(self):
self.sets = {}
def sadd(self, key, *members):
if key not in self.sets:
self.sets[key] = set()
before = len(self.sets[key])
self.sets[key].update(members)
return len(self.sets[key]) - before
def smembers(self, key)…
Refresh Proactive TTL Renewal in Python
This snippet implements a proactive TTL renewal pattern that refreshes a cache expiration before it lapses, using a mock counter to track renewals.
import time
from datetime import datetime, timezone
class TTLRenewer:
def __init__(self, ttl_seconds=10, renew_at=0.5):
self.ttl = ttl_seconds
self.last_renewed = time.time()
self.renew_threshold = ttl_seconds * renew_at
self.renewals = 0
def check_and_renew(self):
if …
Simple Redis Cache Helper in Python
Build a minimal Redis-backed cache with TTL, JSON serialization, and automated fetching to speed up repeated expensive lookups.
import time
import redis
import json
class SimpleCache:
def __init__(self, host="localhost", port=6379, db=0, default_ttl=60):
self.client = redis.Redis(host=host, port=port, db=db, decode_responses=True)
self.default_ttl = default_ttl
def get(self, key):
value = self.client.get(key)…
Cache-Aside Pattern in Python: Per-Service Mock
A Python mock of the cache-aside pattern for a single microservice—lazy-load from a database into an in-memory cache and invalidate on updates.
class ServiceCache:
def __init__(self):
self.database = {"user:1": "Alice", "user:2": "Bob", "user:3": "Charlie"}
self.cache = {}
def get_user(self, user_id):
cache_key = f"user:{user_id}"
if cache_key in self.cache:
print(f"CACHE HIT: {cache_key}")
retu…
Fallback cached response mock in Python
Wraps a mock function with a fallback to a real service and caches results to mask transient failures.
import time
from functools import wraps
class CachedMock:
def __init__(self, cache_ttl=5):
self.cache = {}
self.cache_ttl = cache_ttl
def get(self, key):
cached = self.cache.get(key)
if cached and time.time() - cached["timestamp"] < self.cache_ttl:
return cached["v…
How to Mock Time for Cache TTL Testing in Python
This code demonstrates how to test a cache's TTL expiration logic by mocking time.time with unittest.mock to control the passage of time.
import time
from unittest.mock import patch
class ConfigCache:
def __init__(self, ttl=60):
self.ttl = ttl
self._store = {}
self._timestamps = {}
def get(self, key):
if key not in self._store:
return None
if time.time() - self._timestamps[key] > self.ttl:
…
How to implement OCSP stapling mock in Python
Simulate OCSP stapling with a caching mechanism that mocks certificate status lookups for TLS handshake validation.
import hashlib
import time
class OCSPStapler:
def __init__(self, cert_serial: str, issuer_hash: str):
self.cert_serial = cert_serial
self.issuer_hash = issuer_hash
self.cache = {}
def _mock_query_ocsp(self, serial: str) -> dict:
"""Simulate OCSP responder lookup."""
di…
Mock client credentials machine auth in Python
This code simulates the OAuth2 client-credentials flow for service-to-service calls, generating a mock bearer token with expiry and caching, plus a revoke method, using only the standard library.
import time
import hashlib
import secrets
class MachineAuth:
"""Mock client-credentials machine auth for service-to-service calls."""
def __init__(self, client_id, client_secret):
self.client_id = client_id
self.client_secret = client_secret
self._token = None
self._expire…
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.