Reference library

Python Code Samples

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

17 matches
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…
15 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:
                …
11 0 Open
Functions & basics easy

How to Build Partial Functions with functools.partial in Python

Create reusable partial functions that pre-fill arguments using functools.partial, like making square and cube functions from a general power function.

functools partial higher-order-functions
Python
```python
from functools import partial

def power(base, exponent):
    """Calculate base raised to the exponent power."""
    return base ** exponent

# Create partial functions for common powers
square = partial(power, exponent=2)
cube = partial(power, exponent=3)

if __name__ == "__main__":
    squares = [square(x)…
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 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.

fibonacci memoization functools
Python
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…
14 0 Open
Functions & basics easy

How to Pipe Data Through a List of Transform Functions in Python

Applies a sequence of functions to an initial value using functools.reduce, creating a reusable pipe utility.

functions functional reduce
Python
from functools import reduce

def pipe(data, *transforms):
    return reduce(lambda value, func: func(value), transforms, data)

def double(x):
    return x * 2

def add_one(x):
    return x + 1

def to_string(x):
    return f"Result: {x}"

if __name__ == "__main__":
    initial = 5
    result = pipe(initial, double, …
13 0 Open
Functions & basics easy

How to Use functools.reduce in Python

Apply functools.reduce with operator functions and lambda expressions to aggregate lists into sums, products, maximums, and concatenated strings.

reduce functools lambda
Python
from functools import reduce
import operator

# Sum all numbers in a list using reduce
numbers = [1, 2, 3, 4, 5]
sum_result = reduce(operator.add, numbers)

# Find the maximum value using reduce
max_result = reduce(lambda a, b: a if a > b else b, numbers)

# Multiply all numbers using reduce
product_result = reduce(la…
12 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
Data pipelines & processing easy

How to Reduce Aggregate Counts from Mapped Chunks in Python

Combine a list of mapped chunk dictionaries into a single aggregated count dictionary using functools.reduce.

reduce aggregation dictionary
Python
from functools import reduce
from collections import defaultdict

def aggregate_chunks(mapped_chunks):
    """Combine mapped chunk counts into a single aggregate dict."""
    return reduce(
        lambda acc, chunk: {
            **acc,
            **{k: acc.get(k, 0) + v for k, v in chunk.items()}
        },
       …
14 0 Open
Concurrency & performance easy

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.

asyncio lru_cache memoization
Python
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…
12 0 Open
Concurrency & performance easy

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.

lru-cache memoization functools
Python
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({…
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
Caching & Redis easy

How to Invalidate a Cache in Python with lru_cache

This code demonstrates how to clear the cache of an @lru_cache decorated function in Python using cache_clear(), showing the effect on cached results.

lru_cache cache-invalidation functools
Python
from functools import lru_cache
import time

@lru_cache(maxsize=None)
def expensive_operation(key):
    return f"Computed value for {key} at {time.time():.6f}"

def invalidate_cache():
    expensive_operation.cache_clear()

if __name__ == "__main__":
    print(expensive_operation("alpha"))
    print(expensive_operatio…
13 0 Open
Caching & Redis easy

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.

lru_cache caching functools
Python
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…
15 0 Open
Caching & Redis easy

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.

lru_cache memoization functools
Python
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()}")
13 0 Open
Caching & Redis medium

Implement a Multi-Level Cache with L1 Memory and L2 Redis in Python

This code implements a simple multi-level cache with an in-process L1 cache (via functools.lru_cache) and a mock Redis L2 cache with TTL, falling back to a slow computation on misses.

cache redis lru_cache
Python
import time
from functools import lru_cache


class MockRedis:
    def __init__(self):
        self.store = {}

    def get(self, key):
        return self.store.get(key, None)

    def set(self, key, value, ttl=5):
        self.store[key] = (value, time.time() + ttl)

    def get_ttl(self, key):
        value, expiry…
15 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.