Python weakref Module
Example
Create a weak reference to an object:
import weakref
class Person:
def __init__(self, name):
self.name = name
person = Person('Emil')
weak_person = weakref.ref(person)
print(f'Name: {weak_person().name}')
del person
print(f'After deletion: {weak_person()}')
Try it Yourself »
Definition and Usage
The weakref module creates weak references to objects without preventing them from being garbage collected.
Use it to avoid reference cycles in data structures (like caches, observers, or callbacks) or to maintain references without keeping objects alive.
Note: Not all objects can be weakly referenced. Typical weakref-able objects include class instances, functions, and methods.
Members
Member | Description |
---|---|
CallableProxyType | The type used for weak reference proxies to callable objects. |
ProxyType | The type used for weak reference proxies to non-callable objects. |
ReferenceType | The type used for standard weak references (same as 'ref'). |
WeakKeyDictionary | Dictionary that holds weak references to its keys. |
WeakMethod | Special weak reference for method objects. |
WeakSet | Set that holds weak references to its elements. |
WeakValueDictionary | Dictionary that holds weak references to its values. |
finalize | Register a function to run when an object is about to be destroyed. |
getweakrefcount() | Count how many weak references point to an object. |
getweakrefs() | Get a list of all weak references pointing to an object. |
proxy() | Create a proxy that acts like the object but doesn't keep it alive. |
ref() | Create a weak reference that doesn't prevent garbage collection. |