Skip to main content
🔒 Preview mode. The first 15 Foundations lessons are free; this one is Pro. Start a 7-day trial to unlock the editor, AI hints and the rest of the curriculum. Card required, cancel any time in Dashboard.Start 7-day trial →
← CoursesSenior Deep-DivesModule 7 · Memory, GC, modern typingWeakValueDictionary — caches that let GC do its jobpredict118 / 161
+150 XP
Task
📝 **Task:** Predict the exact output. After `del d` the only strong reference to the Doc is gone; `gc.collect()` reclaims it, and the WeakValueDictionary slot disappears. 📋 Implement the function above. Tests run automatically. 💡 **Hint:** Re-read the theory if you get stuck.
Predict the output

Read the code carefully

import weakref
import gc


class Doc:
    def __init__(self, name):
        self.name = name


cache: weakref.WeakValueDictionary = weakref.WeakValueDictionary()
d = Doc("alpha")
cache["alpha"] = d

print("alpha" in cache)
print(cache["alpha"].name)
print(len(cache))

del d
gc.collect()

print("alpha" in cache)
print(len(cache))

What will the program print? Write here:

💬 Discussion

Be the first to ask a question or share a tip.
Sign in to join the discussion. Reading is free.
Loading discussion…