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.

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:
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:
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:
class Point:
__slots__ = ("x", "y", "__weakref__")
def __init__(self, x, y):
self.x = x
self.y = yWithout __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:
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 imageThe 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:
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] = metadataThe 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:
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:
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:
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:
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 toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.