Reference library

Python Code Samples

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

11 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
Dictionaries & sets medium

LRU Cache with OrderedDict in Python

Implement an LRU cache using collections.OrderedDict to track insertion order and evict the least-recently-used item when capacity is exceeded.

lru-cache ordereddict caching
Python
from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity):
        self.capacity = capacity
        self.cache = OrderedDict()

    def get(self, key):
        if key not in self.cache:
            return -1
        self.cache.move_to_end(key)
        return self.cache[key]

    def put(sel…
13 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({…
14 0 Open
Caching & Redis easy

Cache Warming with Python: Preload Hot Keys

Demonstrates a simple LRU-like cache with a warm method that preloads hot keys with mock values using OrderedDict.

caching ordereddict lru
Python
import time
from collections import OrderedDict

class CacheWarm:
    def __init__(self, capacity=3):
        self.capacity = capacity
        self.cache = OrderedDict()
        self.hot_keys = []

    def warm(self, keys):
        """Preload hot keys into cache with mock values."""
        for key in keys:
          …
17 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…
14 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()}")
12 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…
14 0 Open
Observability & SRE medium

How to Track Cache Hit Ratio in Python

Simulate an LRU cache with hit/miss tracking and compute a real-time hit ratio from random access patterns.

cache lru hit-ratio
Python
import random
import time
from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity: int):
        self.cache = OrderedDict()
        self.capacity = capacity
        self.hits = 0
        self.misses = 0

    def get(self, key):
        if key in self.cache:
            self.hits += 1
     …
12 0 Open
Big data & Spark easy

Cache persist MEMORY_ONLY mock in Python

Mock a MEMORY_ONLY persistence cache in Python with an LRU eviction policy and optional persistence flag.

cache lru mock
Python
import time

class LRUCache:
    def __init__(self, capacity, persistence="MEMORY_ONLY"):
        self.capacity = capacity
        self.persistence = persistence
        self.cache = {}
        self.access_order = []
        self.hits = 0
        self.misses = 0

    def get(self, key):
        if key in self.cache:
 …
13 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.