weakref
The Python weakref
module provides tools for creating weak references to objects for efficient memory management. With weak references, you can cache objects, track their lifecycle, and automatically clean up resources—all without worrying about memory leaks.
Here’s a quick example:
>>> import weakref
>>> class DemoClass:
... pass
...
>>> obj = DemoClass()
>>> weak_obj = weakref.ref(obj)
>>> weak_obj()
<__main__.DemoClass object at 0x...>
>>> del obj
>>> weak_obj() is None
True
Key Features
- Creates weak references to objects
- Allows for callbacks when objects are about to be finalized
- Supports weak dictionaries and sets
- Provides tools for tracking object lifecycle
- Integrates with custom finalization and resource cleanup
- Offers advanced memory management for complex applications
- Helps prevent memory leaks in caches and other data structures
Frequently Used Classes and Functions
Object | Type | Description |
---|---|---|
weakref.ref() |
Class | Creates a weak reference to an object |
weakref.WeakValueDictionary |
Class | Implements a dictionary that stores only weak references to values |
weakref.WeakKeyDictionary |
Class | Implements a dictionary that stores only weak references to keys |
weakref.finalize() |
Function | Registers a callback to be invoked when an object is garbage collected |
weakref.getweakrefcount() |
Function | Returns the number of weak references to an object |
weakref.getweakrefs() |
Function | Returns a list of weak reference objects for an object |
Examples
Using WeakValueDictionary
to manage cache:
>>> import weakref
>>> cache = weakref.WeakValueDictionary()
>>> cache["item"] = DemoClass()
>>> "item" in cache
True
Common Use Cases
- Implementing caches that do not prevent their items from being garbage collected
- Creating mappings where keys or values are allowed to be garbage collected
- Using callbacks for cleanup operations when objects are about to be destroyed
- Tracking objects for resource management or debugging
- Automatically cleaning up related resources or files
- Building data structures that require dynamic object management
Real-World Example
Suppose you want to cache objects but allow them to be garbage collected when they’re no longer in use elsewhere. You can use WeakValueDictionary
to achieve this:
>>> import weakref
>>> class Data:
... def __init__(self, name):
... self.name = name
...
... def __repr__(self):
... return f"Data({self.name!r})"
...
>>> cache = weakref.WeakValueDictionary()
>>> data = Data("item")
>>> cache["data"] = data
>>> del data
>>> "data" in cache
False
In this example, you add data
to the cache, but it’s garbage collected when there are no strong references to it, demonstrating how weakref
helps manage memory efficiently.
Related Resources
Tutorial
Memory Management in Python
Get ready for a deep dive into the internals of Python to understand how it handles memory management. By the end of this article, you’ll know more about low-level computing, understand how Python abstracts lower-level operations, and find out about Python’s internal memory management algorithms.
For additional information on related topics, take a look at the following resources:
- Python Classes: The Power of Object-Oriented Programming (Tutorial)
- Caching in Python Using the LRU Cache Strategy (Tutorial)
- How Python Manages Memory (Course)
- Class Concepts: Object-Oriented Programming in Python (Course)
- Inheritance and Internals: Object-Oriented Programming in Python (Course)
- Python Classes - The Power of Object-Oriented Programming (Quiz)
- Caching in Python With lru_cache (Course)
By Leodanis Pozo Ramos • Updated July 30, 2025