Predict the output
A missing id is looked up twice. How many database reads?
from typing import cast
import redis
r = redis.Redis(decode_responses=True)
DB: dict[int, str] = {}
reads = 0
def find(pid: int) -> str | None:
global reads
hit = cast(str | None, r.get(f"p:{pid}"))
if hit is not None:
return None if hit == "" else hit
reads += 1
val = DB.get(pid)
r.set(f"p:{pid}", val or "", ex=30)
return val
find(999)
find(999)
print(reads)Hint 1 of 1
What does the first call store?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 1
Correct. The first miss stores an empty marker; the second lookup stops at the cache.
Caching 'not found' as an empty marker means the next lookup is answered by Redis. Without it, every request for a missing id goes to the database.
Why not the others?
- B
2. Without the marker it would be 2. - C
0. The first lookup has to ask the database. - D A KeyError. DB.get returns None for missing ids.