2.1. Weakref
A weak reference to an object is not enough to keep the object alive: when the only remaining references to a referent are weak references, garbage collection is free to destroy the referent and reuse its memory for something else. However, until the object is actually destroyed the weak reference may return the object even if there are no strong references to it. 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. [4]
__weakref__
is just an opaque object that references all the weak
references to the current object. It's just an implementation detail that
allows the garbage collector to inform weak references that its referent
has been collected, and to not allow access to its underlying pointer
anymore. The weak reference can't rely on checking the reference count of
the object it refers to. This is because that memory may have been reclaimed
and is now being used by another object. Best case scenario the VM will
crash, worst case the weak reference will allow access to an object it
wasn't originally referring to. This is why the garbage collector must
inform the weak reference its referent is no longer valid. Weak references
form a stack. The top of that stack (the most recent weak reference to an
object) is available via __weakref__
. Weakrefs are re-used whenever
possible, so the stack is typically either empty or contains a single
element. [1]
Garbage collection is simply the process of freeing memory when it is not used/reached by any reference/pointer anymore. Python performs garbage collection via a technique called reference counting (and a cyclic garbage collector that is used to detect and break reference cycles). Using reference counting, GC collects the objects as soon as they become unreachable which happens when the number of references to the object is 0. [2]
The way with which weak references perform the task of NOT protecting the object from being collected by GC, or better to say the way with which they cause an object to be collected by GC is that (in case of a GC that uses reference counting rather than tracing technique) they just don't get to be counted as a reference. Otherwise, if counted, they will be called strong references. [3]