I have been trying to understand how python weak reference lists/dictionaries work. I've read the documentation for it, however I cannot figure out how they work, and what they can be used for. Could anyone give me a basic example of what they do and an explanation of how they work?
(EDIT) Using Thomas's code, when i substitute obj for [1,2,3]
it throws:
Traceback (most recent call last): File "C:/Users/nonya/Desktop/test.py", line 9, in <module> r = weakref.ref(obj) TypeError: cannot create weak reference to 'list' object
To create weak references in python, we need to use the weakref module. The weakref is not sufficient to keep the object alive. A basic use of the weak reference is to implement cache or mappings for a large object. Not all objects can be weakly referenced.
A weak reference permits the garbage collector to collect the object while still allowing the application to access the object. A weak reference is valid only during the indeterminate amount of time until the object is collected when no strong references exist.
A weak reference is just a pointer to an object that doesn't protect the object from being deallocated by ARC. While strong references increase the retain count of an object by 1, weak references do not. In addition, weak references zero out the pointer to your object when it successfully deallocates.
weakref. proxy(object[, callback]) – This returns a proxy to object which uses a weak reference. weakref. getweakrefcount(object) – Return the number of weak references and proxies which refer to object.
The reference count usually works as such: each time you create a reference to an object, it is increased by one, and whenever you delete a reference, it is decreased by one.
Weak references allow you to create references to an object that will not increase the reference count.
The reference count is used by python's Garbage Collector when it runs: any object whose reference count is 0 will be garbage collected.
You would use weak references for expensive objects, or to avoid circle references (although the garbage collector usually does it on its own).
Here's a working example demonstrating their usage:
import weakref import gc class MyObject(object): def my_method(self): print 'my_method was called!' obj = MyObject() r = weakref.ref(obj) gc.collect() assert r() is obj #r() allows you to access the object referenced: it's there. obj = 1 #Let's change what obj references to gc.collect() assert r() is None #There is no object left: it was gc'ed.
Just want to point out that weakref.ref does not work for built-in list because there is no __weakref__
in the __slots__
of list. For example, the following code defines a list container that supports weakref.
import weakref class weaklist(list): __slots__ = ('__weakref__',) l = weaklist() r = weakref.ref(l)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With