What is Weak Reference?

Unlike the references we discussed above, a weak reference is a reference that does not protect the object from getting garbage collected. Why do we want such a thing in the first place?

There are two main applications of weak references:

  • Implement caches for large objects (weak dictionaries).
  • Reduction of Pain from circular references.

To create weak references, Python has provided us with a module named weakref. A point to keep in mind before using weakref is that some builtins such as tuple or int do not support this. list and dict support is either but we can add support through subclassing. Let’s discuss the applications in detail.

Weak References in Python

Python’s memory management algorithm uses a reference counting mechanism for garbage collection, which tracks all reachable objects. All Python objects include a reference count field, which counts how many objects are referencing it. If an object is referenced by another object, then its counter is set to a non-zero number and the object can’t be garbage collected. If the counter reaches zero, the garbage collector will free that object. 

Below is a short example of how can we find the reference count of any object in python.

Python3




import ctypes
 
# list object which is referenced by
# my_list
my_list = [1, 2, 3]
 
# finding the id of list object
my_list_address = id(my_list)
 
# finds reference count of my_list
ref_count = ctypes.c_long.from_address(my_list_address).value
 
print(f"Reference count for my_list is: {ref_count}")


Output:

Reference count for my_list is: 1

So, now as we are clear with the basics of references and garbage collections let’s move to what are weak references and why do we need them?

Similar Reads

What is Weak Reference?

...

Weakref module

Unlike the references we discussed above, a weak reference is a reference that does not protect the object from getting garbage collected. Why do we want such a thing in the first place?...

Contact Us