Can anyone explain usage of weak references?
The documentation doesn’t explain it precisely, it just says that the GC can destroy the object linked to via a weak reference at any time. Then what’s the point of having an object that can disappear at any time? What if I need to use it right after it disappeared?
Can you please explain them with some good examples?
Thanks
The typical use for weak references is if A has a reference to B and B has a reference to A. Without a proper cycle-detecting garbage collector, those two objects would never get GC’d even if there are no references to either from the “outside”. However if one of the references is “weak”, the objects will get properly GC’d.
However, Python does have a cycle-detecting garbage collector (since 2.0!), so that doesn’t count 🙂
Another use for weak references is for caches. It’s mentioned in the
weakrefdocumentation:If the GC decides to destroy one of those objects, and you need it, you can just recalculate / refetch the data.