Skip to the page

Python coding · Build it

An LRU cache decorator without functools

The interviewer asks

Without using functools.lru_cache, write a decorator lru_cache(maxsize) that caches a function's results and evicts the least recently used entry when it's full. Which data structure do you use, and what does each operation cost?

Then

Follow-ups the interviewer asks next

  1. Why is a dict plus a list too slow?
  2. Make it thread-safe. Where do you hold the lock, and why not around the function call?
  3. How do you add a time-to-live?
  4. Are f(1, 2) and f(1, b=2) the same cache entry in your version?

The answer

What a strong answer covers

  • collections.OrderedDict: on a hit move_to_end(key); on a miss compute, insert, and popitem(last=False) when over maxsize. All O(1).
  • Key: (args, tuple(sorted(kwargs.items()))); unhashable arguments raise TypeError (or are not cached, by choice).
  • functools.wraps, plus cache_info() and cache_clear().
  • A plain dict also keeps insertion order: pop and re-insert on a hit, next(iter(d)) for the oldest. From scratch: dict plus a doubly linked list.
  • Thread safety: a lock around the dict reads and writes, not around the slow call (two threads may compute the same key; say whether that's acceptable).
  • TTL: store the time with the value and treat old entries as misses.
  • Edge cases: maxsize 0 or None; returned mutable objects are shared.

The red pen

Common traps

Avoid:a list for recency (O(n) per hit); no wraps.

Practise this out loud

Say your answer out loud to an AI interviewer that follows up, and get a score for it.

Practise by voice

Practise questions like this out loud

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview