Reference library

Python Code Samples

Medium snippets you can copy, study, and run in the browser editor.

11 matches
Functions & basics medium

How to Implement a Trampoline for Tail Recursion in Python

This code implements a trampoline decorator that converts tail-recursive functions into iterative loops, allowing deep recursion without hitting Python's recursion limit.

trampoline tail-recursion decorator
Python
def trampoline(fn):
    """Convert a tail-recursive function into an iterative loop."""
    def wrapper(*args, **kwargs):
        result = fn(*args, **kwargs)
        while callable(result):
            result = result()
        return result
    return wrapper

@trampoline
def factorial(n, acc=1):
    """Tail-recursi…
11 0 Open
Functions & basics medium

How to Invalidate Cache When Arguments Change in Python

A memoization decorator that caches function results keyed by arguments, automatically invalidating when inputs change.

decorators caching memoization
Python
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…
14 0 Open
Comprehensions & generators medium

How to Create a Generator Context Manager in Python with contextlib

Create a custom context manager with the @contextlib.contextmanager decorator to manage resources using a generator function.

contextlib context-manager generator
Python
import contextlib

@contextlib.contextmanager
def temporary_directory():
    """Yield a string and clean up after the block exits."""
    print("Creating temp directory...")
    dir_name = "/tmp/example"
    try:
        yield dir_name
    finally:
        print(f"Removing {dir_name}...")

if __name__ == "__main__":
 …
13 0 Open
AI & LLM integration patterns medium

How to implement exponential backoff for LLM API calls in Python

A decorator that retries flaky LLM API calls with exponential delay, using a mock client to demonstrate the pattern.

exponential-backoff retries llm
Python
import time
import random

class MockLLM:
    def call(self, prompt):
        if random.random() < 0.7:  # 70% chance of transient failure
            raise ConnectionError("API unavailable")
        return f"LLM response for: {prompt}"

def with_exponential_backoff(max_retries=5, base_delay=0.1):
    def decorator(fu…
14 0 Open
System design patterns medium

How to Build a Sidecar Logging Proxy in Python

Wrap any object with a proxy that transparently logs every method call, arguments, return value, and execution time to a file — mimicking a sidecar pattern.

proxy logging sidecar
Python
import logging
import time
from datetime import datetime


class LoggingProxy:
    """Sidecar-style proxy that logs all calls to a wrapped object."""

    def __init__(self, target, log_file="proxy.log"):
        self._target = target
        logging.basicConfig(
            filename=log_file,
            level=loggin…
15 0 Open
Caching & Redis medium

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.

cache ttl jitter
Python
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…
15 0 Open
Caching & Redis medium

How to Cache Function Results in Redis with Python

A Python decorator that caches function results in Redis using TTL, with optional fakeredis for testing without a server.

redis caching decorator
Python
import redis
import json
import time
try:
    import fakeredis
except ImportError:
    fakeredis = None

from functools import wraps


def cache_redis(cache_key_prefix="cache", ttl=60):
    """Decorator to cache function results in Redis."""
    if fakeredis:
        r = fakeredis.FakeStrictRedis()
    else:
        r…
14 0 Open
Reliability & rate limiting medium

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.

retry decorator resilience
Python
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…
13 0 Open
Reliability & rate limiting medium

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.

retry backoff jitter
Python
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…
14 0 Open
Big data & Spark medium

Lazy Evaluation Transform Lineage Mock in Python

Build a mock lineage tracker for data transforms using lazy evaluation and function wrappers in Python.

lazy-evaluation lineage decorator
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…
16 0 Open
Auth & security at scale medium

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.

cors security middleware
Python
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)
        …
16 0 Open

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

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. 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.