The weakref module is used to provide support for weak references. Normally, a reference to an object causes its reference count to increase—effectively keeping the object alive until the reference goes away. A weak reference, on the other hand, provides a way of referring to an object without increasing its reference count. This can be useful in certain kinds of applications that must manage objects in unusual ways. For example, a distributed object system might use weak references so that it can keep track of objects without becoming involved with the low-level details of memory management.

A weak reference is created using the weakref.ref() function as follows:

>>> class A: pass
>>> a = A()
>>> ar = weakref.ref(a)
						# Create a weak reference ...

Get Python: Essential Reference, Third Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.