Code RoomMemo computes same key twice
MediumPrep Room Coding #1865

Memo computes same key twice

Code reviewConcurrencyMid–Senior~25 min

Review this Python deduplicating cache populated by multiple threads.

The write is locked — is this correct under threads?

What a strong answer looks like

Separate real bugs from style. Rank issues by severity, point at the root cause rather than the symptom, and suggest a concrete fix, specific and kind.

0:00 of about 25 min
Mark a line and say what kind of problem it is.0 findings
1import threading
2 
3class Memo:
4 def __init__(self):
5 self._cache = {}
6 self._lock = threading.Lock()
7 
8 def get(self, key, compute):
9 if key not in self._cache: # (1) check
10 value = compute(key) # (2) expensive, no lock
11 with self._lock:
12 self._cache[key] = value # (3) store under lock
13 return self._cache[key] # (4)
Which questions mattered is sealed until you submit. Telling you now would just be handing over the edge cases.