On this page
  1. weakref
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Automatic Cleanup Callbacks with weakref.finalize
  7. 2. Observer Registry Without Memory Leaks (WeakSet)
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

weakref

Prev: wave | Up: stdlib_module | Next: webbrowser
Rel: datetime, zoneinfo, calendar, collections, heapq
Ref: docs.python.org — weakref
Tags: #public #python3 #stdlib


Import

import weakref

Overview

References to objects that do not increment their reference count (ref, WeakValueDictionary, WeakKeyDictionary, WeakSet, finalize), allowing garbage collection once all strong references disappear. Essential for caches, observer registries, and parent/child graphs that would otherwise leak memory.

Quick Start

import gc
import weakref

class CacheEntry:
    pass

cache: weakref.WeakValueDictionary[str, CacheEntry] = weakref.WeakValueDictionary()
item = CacheEntry()
cache["k"] = item
assert cache["k"] is item

del item
gc.collect()
assert "k" not in cache

Implementation Walkthrough

1. Automatic Cleanup Callbacks with weakref.finalize

Prefer weakref.finalize() over __del__ for deterministic cleanup when an object is garbage-collected or at interpreter shutdown:

import gc
import weakref

cleaned: list[str] = []

class Resource:
    def __init__(self, name: str) -> None:
        self.name = name
        self._finalizer = weakref.finalize(self, cleaned.append, name)

r = Resource("temp-handle")
del r
gc.collect()
assert cleaned == ["temp-handle"]

2. Observer Registry Without Memory Leaks (WeakSet)

import gc
import weakref

class Listener:
    pass

listeners: weakref.WeakSet[Listener] = weakref.WeakSet()
obs = Listener()
listeners.add(obs)
assert len(listeners) == 1
del obs
gc.collect()
assert len(listeners) == 0

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes