What does the `weakref` module provide, and when should you reach for a weak reference instead of a normal one?
Answer
A weak reference lets you hold a pointer to an object without increasing its reference count, so the referenced object can still be garbage-collected as if that weak reference did not exist; accessing an expired weak reference gives `None` (or raises, for `weakref.proxy`) instead of a valid object. This is the right tool for caches, observer/listener registries, and parent-child back-references, where a normal reference would either create a reference cycle the collector has to clean up, or would keep an object alive artificially just because a cache or listener list still points to it.
Strong answer includes
- weak references don't increase the reference count
- accessing an expired weakref yields None instead of the object
- used for caches, observer registries, and parent back-references
Practical example
self._parent = weakref.ref(parent)in a child node lets the parent be freed normally when nothing else references it, instead of the child's back-reference keeping it alive forever.