Weak References (weakref)

Published by Brayan K

A weak reference points to an object without keeping it alive, so the garbage collector can reclaim that object as soon as every ordinary (strong) reference is gone.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

A weak reference observes an object without owning its lifetime

An ordinary reference keeps an object reachable. A weak reference lets you ask whether the object still exists without keeping it alive by itself. This helps with caches and observer registries whose bookkeeping should not become the only reason an object remains in memory.

import gc
from weakref import ref

class Item:
    pass

item = Item()
alias = item
handle = ref(item)
del item
gc.collect()
print(handle() is alias)
del alias
gc.collect()
print(handle() is None)

# ✅ Expected output:
# True
# True

Calling the weak reference returns the live object or None after it has been collected. Deleting one variable does not remove other owners. These controlled examples explicitly collect unreachable objects before checking the result; production code should not treat reference deletion as a universal synchronous cleanup event.

from weakref import ref

class Item:
    def __init__(self, name):
        self.name = name

owner = Item("draft")
handle = ref(owner)
item = handle()
if item is not None:
    print(item.name)
print(item is owner)

# ✅ Expected output:
# draft
# True

Retrieve once, store the returned object locally, and then use it. A pattern that tests handle() and later calls handle() again performs two separate lifetime observations; the object might disappear between them in concurrent code. The local item reference keeps the object alive for the operation. Delete or release that local reference when it is no longer needed.

Weak-reference support is a property of the object type

from weakref import ref

ref([])

# ✅ Expected error:
# TypeError: cannot create weak reference to 'list' object

Not every Python object supports weak references. Ordinary user-defined instances usually do; many built-in container instances do not. A suitable subclass can sometimes add support, but do not assume that subclassing every built-in type makes it weak-referenceable.

from weakref import ref

class Items(list):
    pass

items = Items([1, 2])
handle = ref(items)
print(handle() is items)
print(list(handle()))

# ✅ Expected output:
# True
# [1, 2]

For a slotted class, weak-reference support may require __weakref__ in its slot layout. __slots__ & Memory Optimization owns that layout rule. Weak-reference support and hashability are separate: a weak container using objects as keys or set members also needs suitable hashing behavior.

A weak-value cache retains keys but does not guarantee values stay cached

import gc
from weakref import WeakValueDictionary

class Document:
    def __init__(self, text):
        self.text = text

cache = WeakValueDictionary()
document = Document("ready")
cache["draft"] = document
print(cache["draft"].text)
del document
gc.collect()
print("draft" in cache)

# ✅ Expected output:
# ready
# False

WeakValueDictionary holds its values weakly while retaining its keys normally. It is useful when another part of the application owns the objects and the cache merely helps find them. It is not a promise that an expensive result will remain available for a later request. Handle a cache miss by rebuilding or finding another owner.

import gc
from weakref import WeakValueDictionary

class Document:
    pass

cache = WeakValueDictionary()
cache["temporary"] = Document()
gc.collect()
print(len(cache))

# ✅ Expected output:
# 0

The cache is not broken: its contract intentionally avoids ownership. If retention until eviction is required, use a normal cache with an explicit policy instead. functools: lru_cache, partial, reduce owns retained function-result caching.

Weak keys still use equality, and values remain strong references

import gc
from weakref import WeakKeyDictionary

class Key:
    def __init__(self, value):
        self.value = value
    def __hash__(self):
        return self.value
    def __eq__(self, other):
        return isinstance(other, Key) and self.value == other.value

first = Key(1)
second = Key(1)
notes = WeakKeyDictionary()
notes[first] = "old"
notes[second] = "new"
print(len(notes))
print(notes[second])
del first
gc.collect()
print(len(notes))
print(second.value)

# ✅ Expected output:
# 1
# new
# 0
# 1

The equal second key updates the value for the existing entry; it does not replace the weak reference to the original first object. When that first object disappears, the entry disappears even though the equal second object remains alive. Design identity and equality deliberately for weak-key registries.

WeakKeyDictionary holds its values strongly. If a value itself holds its key, that strong path can keep the key alive and defeat the intended weak ownership. Similarly, WeakSet holds members weakly but still requires hashable members; it is not a general list of arbitrary objects.

import gc
from weakref import WeakSet

class Observer:
    pass

first = Observer()
second = Observer()
observers = WeakSet([first, second])
print(len(observers))
del first
gc.collect()
print(len(observers))

# ✅ Expected output:
# 2
# 1

A proxy can become unusable between accesses

import gc
from weakref import proxy

class Item:
    name = "draft"

item = Item()
view = proxy(item)
del item
gc.collect()
print(view.name)

# ✅ Expected error:
# ReferenceError: weakly-referenced object no longer exists

A proxy forwards operations while its referent is alive, then raises ReferenceError after collection. That convenience can hide the lifetime boundary. An explicit ref with a single retrieve-and-check step often makes an optional relationship easier to reason about.

finalize runs cleanup once, but its callback must not retain the owner

from weakref import finalize

events = []
class Resource:
    pass

resource = Resource()
cleanup = finalize(resource, events.append, "released")
print(cleanup.alive)
cleanup()
cleanup()
print(events)
print(cleanup.alive)

# ✅ Expected output:
# True
# ['released']
# False

Calling the finalizer explicitly runs the callback at most once and marks it inactive. A live finalizer can also run when its referent is collected. This is a fallback lifetime mechanism, not a substitute for a context manager when a file, lock or other resource must be released promptly. contextlib: contextmanager, suppress, ExitStack owns deterministic resource scopes.

import gc
from weakref import ref, finalize

events = []
class Resource:
    def close(self):
        events.append("closed")

resource = Resource()
handle = ref(resource)
cleanup = finalize(resource, resource.close)
del resource
gc.collect()
print(handle() is not None)
cleanup()
gc.collect()
print(events)
print(handle() is None)

# ✅ Expected output:
# True
# ['closed']
# True

The stored bound method strongly references its receiver. The finalizer therefore keeps the object alive that it was supposed to observe. Pass a separate cleanup callable and only the independent data it needs, rather than the referent or a bound method of it. A closure capturing the referent can create the same problem.

WeakMethod handles the special lifetime of bound methods

import gc
from weakref import ref, WeakMethod

events = []
class Observer:
    def update(self):
        events.append("updated")

observer = Observer()
bound = observer.update
ordinary = ref(bound)
method = WeakMethod(bound)
del bound
gc.collect()
print(ordinary() is None)
callback = method()
if callback is not None:
    callback()
print(events)
del callback
del observer
gc.collect()
print(method() is None)

# ✅ Expected output:
# True
# ['updated']
# True

A bound method object can be temporary even while its instance is alive. WeakMethod stores the relationship needed to reconstruct that method while the relevant objects exist. The callback local in this example temporarily owns the bound method and therefore its instance, so it is released before the final collection check.

Complete the optional-reference lifetime check

Create a weak reference, remove the owning variable, collect unreachable objects, and test whether the reference has expired. Fill the reference factory and the no-object result.

import gc
from weakref import ref

class Item:
    pass

item = Item()
handle = ___(item)
del item
gc.collect()
print(handle() is ___)

# 👉 replace ___ with ref
# 👉 replace ___ with None

# ✅ Expected output:
# True

Build a registry that does not own its observers

Create two observer objects with names, register them in a WeakValueDictionary, and print the sorted names while both have external owners. Remove one owner, collect unreachable objects, and print the remaining names. Retrieve each weak value once before using it. Do not print the weak-reference objects themselves or rely on dictionary iteration while entries can disappear.

import gc
from weakref import WeakValueDictionary

class Observer:
    def __init__(self, name):
        self.name = name

registry = WeakValueDictionary()
alpha = Observer("alpha")
beta = Observer("beta")
registry["a"] = alpha
registry["b"] = beta

def names():
    found = []
    for key in list(registry.keys()):
        observer = registry.get(key)
        if observer is not None:
            found.append(observer.name)
    return sorted(found)

print(names())
del alpha
gc.collect()
print(names())
print(beta.name)

# ✅ Expected output:
# ['alpha', 'beta']
# ['beta']
# beta

Practice quiz

What does this program print? from weakref import ref class Item: pass item = Item() handle = ref(item) print(handle() is item)

  • True
  • False
  • None
  • ReferenceError

Answer: True. A live weak reference returns the same object while an owner remains.

Why retrieve handle() once into a local variable before using it?

  • It permanently disables collection
  • It creates a temporary strong owner for the operation
  • It turns the object into a copy
  • It makes every object weak-referenceable

Answer: It creates a temporary strong owner for the operation. One retrieve-and-check avoids a second potentially different lifetime observation.

What does this program print? import gc from weakref import WeakValueDictionary class Item: pass cache = WeakValueDictionary() item = Item() cache["x"] = item del item gc.collect() print(len(cache))

  • 1
  • None
  • 0
  • ReferenceError

Answer: 0. The weak cache does not retain the value after its external owner disappears.

What is wrong with finalize(obj, obj.close) as an automatic collection callback?

  • It calls close immediately
  • It never stores the callback
  • It converts close to a string
  • The bound method strongly retains obj

Answer: The bound method strongly retains obj. The cleanup registration itself can keep the referent alive.

What does this program print? from weakref import finalize class Item: pass item = Item() events = [] cleanup = finalize(item, events.append, "done") cleanup() cleanup() print(events)

  • ['done']
  • ['done', 'done']
  • []
  • None

Answer: ['done']. A finalizer callback runs at most once.

What does an expired weakref.ref return when called?

  • ReferenceError
  • None
  • An empty object
  • False unconditionally

Answer: None. A ref exposes absence as None; a proxy instead raises on forwarded access.

What does this program print? from weakref import WeakSet class Item: pass item = Item() items = WeakSet([item]) print(item in items)

  • False
  • None
  • True
  • TypeError

Answer: True. Ordinary user-defined instances support this weak membership while alive.

Why use WeakMethod for an observer’s bound method?

  • It keeps the observer alive forever
  • It forces the method to run
  • It makes methods thread-safe
  • It handles bound-method reconstruction without owning the instance

Answer: It handles bound-method reconstruction without owning the instance. A temporary bound-method object has a lifetime distinct from its receiver.

Continue this course

Related lessons