Weak References
Proxy objects work in two modes: keeping a strong or a weak reference
to the object. The Proxy()
constructor returns a
Proxy object using a strong reference, the WeakProxy()
constructor one
using a weak reference.
Weak references are called weak because they don't keep the
object alive by incrementing the reference count on the
referenced object. Since objects get garbage collected when this
reference count falls down to 0, a weak reference can become
invalid at any time. The mxProxy implementation raises a
LostReferenceError
in case a weak reference to such
an object is used.
This may sound like a pretty flaky feature at first, but the
main pro argument for these weak references is that you can
build up circular references without having to fear about them
not being properly garbage collected. Using strong references
(which do increment the reference count and thus keep the object
alive as long as the reference is around) would produce cycles
in the referencing scheme which the Python garbage collection
(GC) mechanism cannot automatically break causing the cycle to
become unreachable from the Python namespaces: a severe memory
leak.
Weak references in mxProxy work by using a global dictionary of
all objects handled through weak reference Proxies. This
dictionary is checked prior to every action on a weak Proxy and
after its deletion. You can also force a check by calling the
checkweakrefs()
anytime you like, e.g. at regular
intervals.
The dictionary holds a strong reference to the object keeping it
alive until the next check is done. During the check all handled
objects are inspected to see if their reference count has gone
down to 1 (phantom objects: only the dictionary
references them). If this is the case, all weak proxies are
marked defunct and the object is removed from the dictionary
causing it to be garbage collected by the Python GC
mechanism. All subsequent actions on the weak references to this
object will then cause a LostReferenceError
exception to be raised.