Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Cache Function Results with Redis in Python
A RedisCache helper class caches function results using a decorator, with JSON serialization and TTL-based expiry.
import redis
import json
from functools import wraps
class RedisCache:
def __init__(self, host='localhost', port=6379, db=0, ttl=60):
self.client = redis.Redis(host=host, port=port, db=db, decode_responses=True)
self.ttl = ttl
def cached(self, key_prefix):
def decorator(func):
…
Build a Rate Limiter Decorator in Python
This code defines a reusable rate limiter decorator that caps function calls within a sliding time window using a deque and monotonic time.
import time
from collections import deque
def rate_limiter(max_calls: int, period: float):
calls = deque()
def decorator(func):
def wrapper(*args, **kwargs):
now = time.monotonic()
while calls and now - calls[0] >= period:
calls.popleft()
if len(ca…
How to Cap Retry Attempts in Python with a Decorator
Build a reusable retry decorator that caps attempts, adds delays, and lets flaky services fail fast instead of hanging.
import random
from functools import wraps
from time import sleep
def retry(max_attempts, delay=0.1):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
attempts = 0
while attempts < max_attempts:
try:
return func(*args, **kw…
How to Inject Random Latency for Chaos Testing in Python
Mock unreliable services by wrapping functions with a decorator that adds random network-like delays before execution.
import random
import time
from functools import wraps
def inject_latency(func):
@wraps(func)
def wrapper(*args, **kwargs):
latency = random.uniform(0.1, 0.5)
print(f"Injecting {latency:.3f}s latency...")
time.sleep(latency)
return func(*args, **kwargs)
return wrapper
@inje…
How to Retry on Specific Exception Tuples in Python
A decorator-based retry pattern that retries a function only when it raises exceptions specified in a tuple, with configurable retries and delay.
import time
import random
from unittest.mock import patch
def retry_on_exceptions(retries=3, exceptions=(ValueError,), delay=0.1):
def decorator(func):
def wrapper(*args, **kwargs):
for attempt in range(retries):
try:
return func(*args, **kwargs)
…
Retry with Exponential Backoff and Jitter in Python
A decorator-style retry wrapper that retries a flaky function with exponential backoff plus random jitter, then raises after the last attempt fails.
import random
import time
def retry_with_backoff(func, max_retries=3, base_delay=0.5, max_jitter=0.1):
for attempt in range(max_retries + 1):
try:
return func()
except Exception as e:
if attempt == max_retries:
raise
delay = base_delay * (2 ** at…
Lazy Evaluation Transform Lineage Mock in Python
Build a mock lineage tracker for data transforms using lazy evaluation and function wrappers in Python.
import functools
def lazy_transform(pipeline):
"""Build a mock lineage tracker using lazy evaluation."""
lineage = []
def wrap(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
lineage.append({"transform": func.__name__, "a…
How to Mock a CORS Allow Origin Whitelist in Python
A decorator-based mock of a CORS middleware that whitelists allowed origins and injects proper Access-Control-Allow-Origin headers while rejecting others.
from functools import wraps
class MockCORSConfig:
def __init__(self, allowed_origins):
self.allowed_origins = allowed_origins
def is_origin_allowed(self, origin):
return origin in self.allowed_origins
def cors_middleware(config):
def decorator(handler):
@wraps(handler)
…
How to hide incomplete mock features with a Python feature toggle
A simple decorator-based feature toggle that returns a placeholder when a mock feature is disabled, so incomplete code can ship safely.
import functools
class FeatureToggle:
def __init__(self, enabled=False):
self.enabled = enabled
def feature(self, func=None):
"""Decorator to conditionally enable a feature."""
if func is None:
return self.feature
@functools.wraps(func)
def wrapper(*args,…
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.