🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this guide, you'll explore Python's weakref module, which creates weak references to objects. Learn its features and examples for memory management.
The weakref module in Python provides functions for creating weak references to objects. Weak references allow the referenced object to be garbage collected when there are no strong references to it, which can help with memory management in certain scenarios.
Table of Contents
- Introduction
- Weak Reference Types
refproxy
- Weak Reference Methods
callback
- Weak Reference Collections
WeakKeyDictionaryWeakValueDictionaryWeakSet
- Examples
- Creating Weak References
- Using Callbacks with Weak References
- Using Weak Reference Collections
- Conclusion
7References
Introduction
The weakref module provides support for weak references in Python. A weak reference allows an object to be referenced without preventing it from being garbage collected. This is useful for caching, observing, and other scenarios where you want to avoid creating reference cycles that would prevent garbage collection.
Weak Reference Types
ref
The ref function creates a weak reference to an object. The referenced object can be retrieved using the weak reference.
import weakref
class MyClass:
pass
obj = MyClass()
weak_ref = weakref.ref(obj)
print(weak_ref)
print(weak_ref())
Output:
<weakref at 0x0000025235A427F0; to 'MyClass' at 0x0000025235A35CD0>
<__main__.MyClass object at 0x0000025235A35CD0>
proxy
The proxy function creates a proxy object that behaves like a weak reference but automatically dereferences itself.
import weakref
class MyClass:
def __init__(self, value):
self.value = value
obj = MyClass(10)
weak_proxy = weakref.proxy(obj)
print(weak_proxy.value)
Output:
10
Weak Reference Methods
callback
A callback function can be registered to be called when the referenced object is about to be finalized.
import weakref
class MyClass:
pass
def on_finalize(ref):
print("Object is being garbage collected")
obj = MyClass()
weak_ref = weakref.ref(obj, on_finalize)
del obj
Output:
Object is being garbage collected
Weak Reference Collections
WeakKeyDictionary
A WeakKeyDictionary is a dictionary that holds weak references to its keys. When a key is garbage collected, the corresponding item is automatically removed from the dictionary.
import weakref
class MyClass:
pass
obj = MyClass()
weak_dict = weakref.WeakKeyDictionary()
weak_dict[obj] = "value"
print(list(weak_dict.keys()))
del obj
print(list(weak_dict.keys()))
Output:
[<__main__.MyClass object at 0x0000016866255E50>]
[]
WeakValueDictionary
A WeakValueDictionary is a dictionary that holds weak references to its values. When a value is garbage collected, the corresponding item is automatically removed from the dictionary.
import weakref
class MyClass:
pass
obj = MyClass()
weak_dict = weakref.WeakValueDictionary()
weak_dict["key"] = obj
print(list(weak_dict.values()))
del obj
print(list(weak_dict.values()))
Output:
[<__main__.MyClass object at 0x000002511F655E50>]
[]
WeakSet
A WeakSet is a set that holds weak references to its elements. When an element is garbage collected, it is automatically removed from the set.
import weakref
class MyClass:
pass
obj = MyClass()
weak_set = weakref.WeakSet()
weak_set.add(obj)
print(list(weak_set))
del obj
print(list(weak_set))
Output:
[<__main__.MyClass object at 0x000002B5C7145E20>]
[]
Examples
Creating Weak References
Create a weak reference to an object and retrieve it.
import weakref
class MyClass:
pass
obj = MyClass()
weak_ref = weakref.ref(obj)
print(weak_ref()) # Retrieve the referenced object
Output:
<__main__.MyClass object at 0x000001C61FF45C70>
Using Callbacks with Weak References
Register a callback to be called when the referenced object is about to be finalized.
import weakref
class MyClass:
pass
def on_finalize(ref):
print("Object is being garbage collected")
obj = MyClass()
weak_ref = weakref.ref(obj, on_finalize)
del obj # Trigger garbage collection
Output:
Object is being garbage collected
Using Weak Reference Collections
Use WeakKeyDictionary to manage objects with weak references.
import weakref
class MyClass:
pass
obj = MyClass()
weak_dict = weakref.WeakKeyDictionary()
weak_dict[obj] = "value"
print(list(weak_dict.keys()))
del obj
print(list(weak_dict.keys()))
Output:
[<__main__.MyClass object at 0x0000021C86375E50>]
[]
Conclusion
The weakref module in Python provides functions for managing references to objects without preventing their garbage collection. This is especially useful in scenarios like caching, observing, and managing reference cycles, helping to optimize memory usage and program performance.
References
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment