views:

96

answers:

1

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, Boda Cydo.

+5  A: 

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 weakref documentation:

A primary use for weak references is to implement caches or mappings holding large objects, where it’s desired that a large object not be kept alive solely because it appears in a cache or mapping.

If the GC decides to destroy one of those objects, and you need it, you can just recalculate / refetch the data.

Nicolás
Hmm... I didn't realize that you mentioned caches... I suppose I should delete my answer and read more carefully next time :-).
Tom
Well, it was just a one-liner mention of caches. I then expanded the answer, *after* you had posted yours :)
Nicolás
Ok, well that at least I'm not crazy :-). It doesn't say your post was edited though. Either way.. I liked your answer after I read it again... and I don't want to come off as reputation-hungry :-).
Tom