Python Glossary Русский

all Python 3weakrefterm

weakref

module

Weak references: point to an object without keeping the garbage collector from freeing it. The basis of caches and registries.

Syntax

import weakref

Use weakref when a helper structure — a cache, an observer registry — must not keep objects alive: a WeakValueDictionary forgets a value as soon as no ordinary references to the object remain. You cannot take a weak reference to int, str, tuple or plain list and dict — that raises TypeError. For cleanup when an object dies, weakref.finalize is more reliable than __del__.

Examples

import weakref
class Node:
    pass
n = Node()
r = weakref.ref(n)
print(r() is n)  # → True
del n
print(r())  # → None — объект удалён, слабая ссылка его не удержала

See also

Open in the full glossarydocs.python.orgReport an inaccuracy