Python coding · Build it
An LRU cache decorator without functools
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe 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
- Why is a dict plus a list too slow?
- Make it thread-safe. Where do you hold the lock, and why not around the function call?
- How do you add a time-to-live?
- Are
f(1, 2)andf(1, b=2)the same cache entry in your version?
The answer
What a strong answer covers
collections.OrderedDict: on a hitmove_to_end(key); on a miss compute, insert, andpopitem(last=False)when overmaxsize. All O(1).- Key:
(args, tuple(sorted(kwargs.items()))); unhashable arguments raiseTypeError(or are not cached, by choice). functools.wraps, pluscache_info()andcache_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:
maxsize0 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 voicePractise 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.