Implementing weak references in Python

time to read 1 min | 167 words

Normal Python references to objects increment the object’s reference count thus preventing it from being garbage collected.

If a user desires creating weak references, the weakref module can be used:

import weakref

class Rezha(object): pass

To create a weak reference, the ref class is used:

# object instance
rezha = Rezha()
# weak reference to our object
r = weakref.ref(rezha)

Then, you can call the reference object:

print(r)
# <weakref at 0x01414E40; to 'Rezha'...>
print(r())
# <__main__.Rezha object at 0x0133D270>

If the reference no longer exists, calling it returns None:

del rezha
print(r())
# None

To check the existence of the reference:

if r is not None:
  # reference exists!

Weak references are often used to implement caching for large objects, but also for implementing cyclic references.

Imagine the case where object X references object Y and Y references X. Without a cycle-detecting garbage collector, the two objects would never be garbage collected. However, if one of the references is weak, they will be properly garbage collected.