What is Python's weakref module?
Why Interviewers Ask This
This tests whether you can apply Python knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.
Answer
The weakref module provides weak reference objects that refer to an object without increasing its reference count, allowing the object to be garbage collected when no strong references exist. Create: import weakref; obj = MyObject(); ref = weakref.ref(obj); print(ref()) — calling the ref returns the object or None if collected. WeakValueDictionary: a dict that holds weak references to values — entries vanish when values are collected. WeakKeyDictionary: entries vanish when keys are collected. WeakSet: like WeakValueDictionary but a set. Use cases: caches (let entries be freed when not used elsewhere), preventing memory leaks in observer patterns (listener holding reference to subject), and circular references. Contrast: regular references keep objects alive; weak references observe without keeping alive.
Common Mistake
Candidates often give textbook answers here. Interviewers are more impressed when you relate the concept to a specific problem you solved in a real Python project.