Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

33 matches
Functions & basics easy

Build a Context Manager in Python with contextlib.contextmanager

Create a reusable context manager that safely opens and closes files using the contextlib contextmanager decorator.

context manager contextlib file handling
Python
from contextlib import contextmanager

@contextmanager
def managed_file(filename, mode='r'):
    """Context manager that opens and closes a file safely."""
    file = open(filename, mode)
    yield file
    file.close()

if __name__ == "__main__":
    # Write a sample file
    with managed_file("sample.txt", "w") as f…
15 0 Open
Functions & basics easy

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.

lru_cache caching decorators
Python
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…
16 0 Open
Functions & basics easy

Create a retry decorator with max attempts in Python

A decorator that retries a function up to a specified number of times when it raises an exception, with an optional delay between attempts.

decorator retry error-handling
Python
import functools
import time


def retry(max_attempts, delay=0.1):
    """Retry a function up to max_attempts times on exception."""
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(1, max_attempts + 1):
                try:
                …
12 0 Open
Functions & basics easy

How to Build a Simple Decorator That Logs Function Calls in Python

This code shows how to create a reusable decorator that logs each function call, including arguments, return value, and execution time.

decorator logging functools
Python
import functools
import time

def log_calls(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with args={args}, kwargs={kwargs}")
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} return…
11 0 Open
Functions & basics easy

How to Create a Timing Decorator in Python

A Python decorator that measures and prints the execution time of any function using time.perf_counter.

decorator timing perf_counter
Python
import time
from functools import wraps


def timing_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        end = time.perf_counter()
        elapsed = end - start
        print(f"{func.__name__} took {elapsed:.6f} seconds"…
11 0 Open
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
Functions & basics easy

How to Use singledispatch for Type-Based Overloading in Python

This code demonstrates Python's functools.singledispatch decorator to create functions that behave differently based on the type of their first argument.

singledispatch overloading functools
Python
from functools import singledispatch

@singledispatch
def process(value):
    return f"Unknown type: {type(value).__name__}"

@process.register(int)
def _(value):
    return f"Integer: {value * 2}"

@process.register(str)
def _(value):
    return f"String: {value.upper()}"

@process.register(list)
def _(value):
    re…
12 0 Open
Functions & basics easy

How to Write a Python Decorator with functools.wraps

Create a decorator that wraps a function while preserving its metadata using functools.wraps.

decorator functools wraps
Python
from functools import wraps


def logger(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper


@logger
def greet(name):
    """Return a friendly greeting."""
    return f"Hello, {name}!"


if __name__ == "__main__":…
12 0 Open
OOP & classes easy

Composition over Inheritance: How to Build a Wallet Account in Python

Demonstrates composition by wrapping a WalletAccount class in an AuditedWallet decorator-like class to add behavior without changing the original class.

composition design-patterns oop
Python
class WalletAccount:
    def __init__(self, owner, balance=0.0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Deposit must be positive")
        self.balance += amount
        return self.balance

    def withdraw(self, …
13 0 Open
OOP & classes easy

How to Create Static Methods in a Python Class

Shows how to define and call static methods inside a class using @staticmethod, with utility functions that don't need instance or class state.

static-method oop class
Python
class MathUtils:
    """Utility class demonstrating static methods."""
    
    @staticmethod
    def add(a, b):
        """Return the sum of two numbers."""
        return a + b
    
    @staticmethod
    def multiply(a, b):
        """Return the product of two numbers."""
        return a * b
    
    @staticmethod
…
14 0 Open
OOP & classes easy

How to Implement the Decorator Pattern in Python to Add Behavior

This Python code demonstrates the decorator pattern by wrapping a function to add logging behavior without modifying the original function.

decorator pattern logging
Python
import functools

def logger(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with {args} {kwargs}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

@logger
def add(a, b):
   …
11 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
Modern tooling easy

How to Parametrize Tests in Python with pytest

This code demonstrates how to use pytest's @pytest.mark.parametrize decorator to run a single test function against multiple input sets, ensuring comprehensive coverage with minimal code duplication.

pytest parametrize testing
Python
import pytest


def multiply(a, b):
    return a * b


@pytest.mark.parametrize("x, y, expected", [
    (2, 3, 6),
    (4, 5, 20),
    (0, 10, 0),
    (7, 1, 7),
])
def test_multiply(x, y, expected):
    result = multiply(x, y)
    assert result == expected, f"multiply({x}, {y}) = {result}, expected {expected}"


if _…
15 0 Open
Concurrency & performance easy

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.

functools memoization performance
Python
```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 {…
14 0 Open
Concurrency & performance easy

How to Vectorize a Function with a Pure Python Fallback

Create a decorator that calls a scalar function directly for a single value and routes list inputs to a pure-Python fallback for vectorized processing without NumPy.

vectorization decorator fallback
Python
import math


def fallback_vectorize(func, fallback=None):
    """Vectorize a scalar function with a pure-Python fallback for lists."""
    if fallback is None:
        fallback = lambda x: [func(i) for i in x]

    def wrapped(*args):
        if len(args) == 1 and isinstance(args[0], (list, tuple)):
            retur…
14 0 Open
Testing & modern typing easy

How to Parametrize pytest Tests with Multiple Input Cases in Python

This code shows how to use pytest's @pytest.mark.parametrize decorator to run the same test function across multiple input-output combinations, checking that an add function behaves correctly for each case.

pytest parametrize testing
Python
import pytest

def add(a, b):
    return a + b


@pytest.mark.parametrize("a,b,expected", [
    (1, 2, 3),
    (5, 5, 10),
    (-1, 1, 0),
    (0, 0, 0),
    (10, -3, 7),
])
def test_add(a, b, expected):
    assert add(a, b) == expected


if __name__ == "__main__":
    pytest.main([__file__, "-v"])
14 0 Open
Testing & modern typing easy

How to freeze time in Python tests with freezegun

Use the freezegun decorator to freeze datetime.now() at a fixed timestamp so tests that depend on current time run deterministically.

freezegun datetime testing
Python
from datetime import datetime
from freezegun import freeze_time


@freeze_time("2024-01-15 12:30:00")
def test_frozen_time():
    now = datetime.now()
    return now


if __name__ == "__main__":
    result = test_frozen_time()
    print(result)
15 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
System design patterns easy

How to Mock a Metrics Decorator in Python with unittest.mock

This code demonstrates a timing decorator that wraps a function to measure execution time and prints the duration, with a unit test using unittest.mock to patch the print function and assert it was called.

decorators unittest.mock metrics
Python
import time
from functools import wraps
from unittest.mock import patch

def add_metrics(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        elapsed = time.perf_counter() - start
        print(f"{func.__name__} took {elapsed:.6f}s…
15 0 Open
API design & gRPC easy

How to Implement RBAC Permission Checks with a Route Decorator in Python

Build a reusable Python decorator that checks a user's role against allowed roles and raises a custom PermissionError when access is denied.

decorator rbac permissions
Python
from functools import wraps
from enum import Enum

class Role(Enum):
    ADMIN = "admin"
    MODERATOR = "moderator"
    USER = "user"

class PermissionError(Exception):
    pass

def require_role(*allowed_roles):
    def decorator(func):
        @wraps(func)
        def wrapper(user_role, *args, **kwargs):
          …
13 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

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.