1 min read

Python Weakref Module

The weakref module allows the Python programmer to create weak references to objects. A weak reference to an object is not enough to keep the object alive: if the only remaining references to a referent are weak references, garbage collection is free to destroy the referent and reuse its memory for something else.

Importing the Module

import weakref

Creating Weak References

You can create a weak reference using weakref.ref().

import weakref

class MyClass:
    def my_method(self):
        print("Hello")

obj = MyClass()
r = weakref.ref(obj)

print(r) # Output: <weakref at ...; to 'MyClass' at ...>

Accessing the Object

To access the original object, you call the weak reference object.

print(r()) # Output: <__main__.MyClass object at ...>
r().my_method() # Output: Hello

If the object has been garbage collected, calling the weak reference returns None.

del obj
print(r()) # Output: None

Weak Dictionaries

The module also provides WeakValueDictionary and WeakKeyDictionary.

WeakValueDictionary

A mapping class that references values weakly. Entries in the dictionary will be discarded when no strong reference to the value exists any more.

d = weakref.WeakValueDictionary()

programming/python/python