Intermediate LevelPython
How does the weakref module allow referencing heavy objects without incrementing their reference count?
❓ Interview Prompt: Explain `weakref` module, Weak References (`weakref.ref`), `WeakValueDictionary`, avoiding circular reference memory leaks, and CPython GC.
In CPython, an object is deallocated when its reference count drops to zero. 'weakref' allows creating references to objects without incrementing their reference count:
Use Cases:
•
In-Memory Caches ('WeakValueDictionary'): Cached items are automatically garbage-collected when no strong references exist elsewhere in application memory!
Code Implementation Example
python
import weakref
class HeavyImage:
def __init__(self, name):
self.name = name
img = HeavyImage('large_photo.png')
cache = weakref.WeakValueDictionary()
cache['photo'] = img
print('In Cache:', 'photo' in cache) # True
del img # Delete sole strong reference!
print('In Cache after del:', 'photo' in cache) # False! Auto-removed!💡Caching objects without preventing garbage collection using WeakValueDictionary.
🎯 Interview Key Takeaway
Use weakref.WeakValueDictionary for in-memory caches to allow automatic garbage collection when objects are unused.
#weakref#Memory Management#Garbage Collection#Intermediate
Back to all Python Questions→