Python Glossary Русский

all Python 3weakrefterm

weakref.ref

weak references

A weak reference: it lets you reach an object without keeping it alive. Calling r() returns the object, or None once it is gone.

Syntax

r = weakref.ref(obj, callback=None); r()

In CPython an object is freed the moment its last ordinary reference disappears — right after del or when a function returns; objects caught in reference cycles wait for the gc collector. You cannot create a weak reference to int, str, list, tuple or dict (TypeError): those types lack the __weakref__ slot to save memory. A subclass of list, dict or str does support it, a subclass of int or tuple does not. weakref.ReferenceType is the same object as weakref.ref.

Examples

import weakref
class Node:
    pass
n = Node()
r = weakref.ref(n)
print(r() is n)  # → True
del n
print(r())  # → None
import weakref
class MyList(list):
    pass
print(weakref.ref(MyList()) is not None)  # → True
try:
    weakref.ref([1, 2])
except TypeError:
    print('TypeError')  # → TypeError

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy