Concurrency & performance
asyncio, threading, multiprocessing, and profiling-friendly performance patterns.
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.
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…
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.
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({…
Browse by section
Each section groups closely related Python snippets.
Concurrency & performance — Python code examples
What you will find here
This page collects concurrency & performance snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
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.