Question presented to candidate:
"What is a weak reference in Python, and how is it different from a normal reference? Give me a situation where you would use one, and tell me what the weakref module offers beyond weakref.ref."
What a strong answer should cover:
- A weak reference refers to an object without increasing its reference count, so it does not keep the object alive; calling the ref returns the object, or
Noneonce it has been collected. - Use cases: caches that should not keep values alive (
WeakValueDictionary), attaching data to objects you do not own (WeakKeyDictionary), observer/listener lists (WeakSet,WeakMethod), and back-pointers in trees that would otherwise create cycles. - Callbacks on
weakref.ref,weakref.proxy(raisesReferenceErrorwhen dead), andweakref.finalizefor cleanup. - Limits:
int,str,tuple,listanddictinstances cannot be weakly referenced (subclasses oflist/dictcan); classes with__slots__need"__weakref__"in the slots. - The bound-method trap:
weakref.ref(obj.method)dies immediately, which is whyWeakMethodexists.
Code / implementation expected: Yes β a small WeakValueDictionary cache or a listener registry that cleans itself up.