On this page
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
- Built-in
int,str,tuple,list, anddictcannot be weak-referenced directly: Subclass them or wrap them in a normal class (or@dataclass(slots=False)/@dataclass(slots=True, weakref_slot=True)). - Classes with
__slots__require"__weakref__"in__slots__(orweakref_slot=Trueon dataclasses) to support weak references. - Always check
obj = ref(); if obj is not None:: A weak reference returnsNoneonce its referent is collected—never callref()twice expecting the same non-Noneresult.
Common Functions
- weakref.getweakrefcount() —
getweakrefcount(object, /)— Return the number of weak references to 'object'. - weakref.getweakrefs() —
getweakrefs(object, /)— Return a list of all weak reference objects pointing to 'object'. - weakref.proxy() —
proxy(object, callback=None, /)— Create a proxy object that weakly references 'object'.
Classes & Objects
- weakref.CallableProxyType —
weakref.CallableProxyTypeclass. - weakref.finalize — Class for finalization of weakrefable objects finalize(obj, func, *args, **kwargs) returns a callable finalizer object which will be called when obj is garbage collected. The (Methods:
.alive(),.atexit(),.detach(),.peek()) - weakref.ProxyType —
weakref.ProxyTypeclass. - weakref.ref —
weakref.refclass. - weakref.ReferenceType —
weakref.ReferenceTypeclass. - weakref.WeakKeyDictionary — Mapping class that references keys weakly. (Methods:
.clear(),.copy(),.get(),.items(),.keyrefs(),.keys()) - weakref.WeakMethod — A custom
weakref.refsubclass which simulates a weak reference to a bound method, working around the lifetime problem of bound methods. - weakref.WeakSet —
weakref.WeakSetclass. (Methods:.add(),.clear(),.copy(),.difference(),.difference_update(),.discard()) - weakref.WeakValueDictionary — Mapping class that references values weakly. (Methods:
.clear(),.copy(),.get(),.items(),.itervaluerefs(),.keys())
Constants & Attributes
weakref.ProxyTypes(tuple) =(<class 'weakref.ProxyType'>, <class 'weakref.CallablePro...
Linked from
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/wave
- tuts/python3/stdlib_module/weakref/CallableProxyType
- tuts/python3/stdlib_module/weakref/finalize
- tuts/python3/stdlib_module/weakref/getweakrefcount
- tuts/python3/stdlib_module/weakref/getweakrefs
- tuts/python3/stdlib_module/weakref/proxy
- tuts/python3/stdlib_module/weakref/ProxyType
- tuts/python3/stdlib_module/weakref/ref
- tuts/python3/stdlib_module/weakref/ReferenceType
- tuts/python3/stdlib_module/weakref/WeakKeyDictionary
- tuts/python3/stdlib_module/weakref/WeakMethod
- tuts/python3/stdlib_module/weakref/WeakSet
- tuts/python3/stdlib_module/weakref/WeakValueDictionary
- tuts/python3/stdlib_module/webbrowser
- tuts/python3/tutorials/advanced_python_internals/memory_management_and_internals
Related notes
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/wave Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/weakref/CallableProxyType Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/weakref/finalize Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/weakref/getweakrefcount Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/weakref/getweakrefs Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/weakref/proxy Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/weakref/ProxyType Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/weakref/ref Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/weakref/ReferenceType Linked here; links to this page; shared tags: #stdlib