You’ve used @lru_cache to speed up a slow function, and it worked... until your app started eating RAM because the cache never forgot anything.
from functools import lru_cache
@lru_cache
def fib(n):
return fib(n-1) + fib(n-2) # ← Cache grows forever!👉Here’s what’s really happening:
A decorator is just a function that wraps another function. When you write @lru_cache, Python replaces your fib with a new version that remembers every answer it’s ever given. Cool😄 until n goes from 1 to 100,000.
✅ Fix it like a pro:
from functools import lru_cache
@lru_cache(maxsize=128) # Only keep last 128 results
def fib(n):
if n > 1000:
return manual_calc(n) # Skip cache for huge inputs
return fib(n-1) + fib(n-2)Now the cache stays small, predictable, and safe.
📌Bonus: Write your own @timerdecorator in 5 lines. no more time.time() spam.