Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Weak References: Track Objects Without Blocking Cleanup

Python weak references let you track and cache objects without keeping them alive. Learn how to use weakref.ref, WeakValueDictionary, WeakKeyDictionary, WeakSet, and weakref.finalize with practical examples.

~4 min readPython
#weakref#garbage collection#memory management#caching
Illustration of a Python object held by a solid strong reference and a translucent weak reference that fades away, showing the object can be garbage collected.

What a Weak Reference Actually Is

Python weak references let you track or cache objects without keeping them alive. A weak reference is a reference to an object that does not stop the garbage collector from reclaiming that object once all strong references are gone. When the object is collected, the weak reference returns None instead of the object.

This matters in long-running applications where caches, registries, or observer lists can accidentally hold objects in memory far longer than needed. A strong reference in a dictionary value, for example, keeps the object alive for as long as the dictionary exists. A weak reference does not.

The weakref module in the standard library provides the tools for working with weak references.

Creating and Using a Weak Reference

The core API is weakref.ref(). You pass an object to it, and it returns a reference object that you can call like a function to retrieve the original object:

python
import weakref class Widget: def __init__(self, name): self.name = name widget = Widget("panel") ref = weakref.ref(widget) # Retrieve the object through the weak reference print(ref().name) # panel # Remove the strong reference del widget # The object is now eligible for collection. # In CPython this becomes None immediately; other implementations may collect later. print(ref())

The weak reference object is callable. Calling it returns the referent if it is still alive, or None if it has been collected. Always check the result before using it. If you need to use the referent, keep the result of ref() in a local variable; that local variable is a normal strong reference and prevents the object from being collected while you use it.

Which Objects Can Be Weakly Referenced

Not every Python object supports weak references. Instances of most user-defined classes do, but several built-in types do not:

python
import weakref # This raises TypeError weakref.ref([1, 2, 3])

The exact built-in list, dict, str, int, tuple, and set types do not support weak references, although subclasses of those types can. If you need to track one of these values, wrap it in a small class or hold it inside a container that supports weak references.

For a class that uses __slots__ and does not inherit a __weakref__ slot from a base class, you must include __weakref__ in the slot list:

python
class Point: __slots__ = ("x", "y", "__weakref__") def __init__(self, x, y): self.x = x self.y = y

Without __weakref__ in the slots, instances of the class cannot be weakly referenced and weakref.ref() raises TypeError.

WeakValueDictionary for Caches

weakref.WeakValueDictionary is a dictionary whose values are weakly referenced. When a value is garbage collected, its entry is removed from the dictionary automatically. This is the standard tool for building caches that do not keep their contents alive indefinitely:

python
import weakref class Image: def __init__(self, path): self.path = path cache = weakref.WeakValueDictionary() def load_image(path): image = cache.get(path) if image is None: image = Image(path) cache[path] = image return image

The cache holds the image only while something else in the program also holds a reference to it. Once the last caller releases the image, the entry disappears from the cache. This prevents a cache from becoming a memory leak in a long-running process.

WeakKeyDictionary for Tracking Objects

weakref.WeakKeyDictionary is the inverse: the keys are weakly referenced, and the entry is removed when a key is collected. This is useful when you need to attach metadata to objects without keeping them alive:

python
import weakref class Session: def __init__(self, user_id): self.user_id = user_id session_metadata = weakref.WeakKeyDictionary() def attach_metadata(session, metadata): session_metadata[session] = metadata

The metadata is removed automatically when the session object is garbage collected. This avoids the common problem of a registry that grows without bound because it holds strong references to keys that no longer exist elsewhere.

WeakSet for Membership Tracking

weakref.WeakSet is a set whose elements are weakly referenced. It is useful for tracking live instances of a class without preventing their collection:

python
import weakref class Connection: _live = weakref.WeakSet() def __init__(self): Connection._live.add(self) @classmethod def live_count(cls): return len(cls._live)

Each new Connection instance registers itself in the weak set. When an instance is no longer referenced anywhere else, it is removed from the set automatically. This pattern is common for diagnostics, monitoring, and resource cleanup.

Callbacks and Finalization with weakref.finalize

weakref.finalize registers a callback that runs when the referent is garbage collected. This is a more reliable alternative to __del__ because it avoids the problems __del__ has with cyclic references and interpreter shutdown:

python
import weakref class TempFile: def __init__(self, path): self.path = path self._finalizer = weakref.finalize(self, self._cleanup, path) @staticmethod def _cleanup(path): print(f"Removing {path}")

The callback receives the arguments you pass at registration time, not the object itself. This avoids keeping a strong reference to the object inside the callback, which would defeat the purpose of the finalizer.

Common Pitfalls and Edge Cases

weakref.ref objects are hashable when their referent is hashable, so they can normally be used in sets and as dictionary keys. A class that sets __hash__ = None produces instances whose weak references are not hashable either. If you need key behavior tied to object identity, prefer WeakKeyDictionary rather than putting weak references in a plain dictionary.

A more subtle issue is that the referent can disappear between two weak-reference calls. Do not write this:

python
if ref() is not None: ref().do_something()

The object can be collected between the two calls to ref(); the second call may return None, and the method call will fail. Instead, keep the result in a strong local variable. The local variable itself protects the object for the duration of the operation:

python
obj = ref() if obj is not None: obj.do_something()

Memory and Performance Considerations

Weak references add a small overhead. Each weak reference requires an allocation, and the garbage collector must process the weak reference when the referent is collected. For most applications this cost is negligible.

The bigger concern is correctness. A cache built with WeakValueDictionary can evict entries at any time, so code that assumes a cached value is always present will fail. Always handle the miss case, as in the image loader example above.

weakref.finalize works correctly even when objects participate in reference cycles, which is one reason it is preferred over __del__ for cleanup logic. Weak references themselves do not remove the need for the cyclic garbage collector.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.