- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Weak References
To create weak references in python, we need to use the weakref module. The weakref is not sufficient to keep the object alive. A basic use of the weak reference is to implement cache or mappings for a large object.
To use this module, we should import it using −
Not all objects can be weakly referenced. Some built-in types like tuple or int, do not support weak reference. There are some classes and methods related to weak reference.
Class weakref.ref(object[, callback])
It will return a weak reference to the object. When the referent is still alive, the actual object can be retrieved by calling the reference object, but when the actual object is not present, it will return None.
Method weakref.proxy(object[, callback])
This method is used to return a proxy for the object, which are using weak reference. The returned object may be either ProxyType or CallableProxyType.
This method is used to return the number of weak references and proxies of the objects.
This method is used to return a list of weak references and proxies objects.
import weakref class my_list(list): pass new_list = my_list('String') #Use my_list class to define a list print(new_list) weak_ref = weakref.ref(new_list) new_weak_list = weak_ref() new_proxy = weakref.proxy(new_list) print(new_weak_list) print('The object using proxy: ' + str(new_proxy)) if new_list is new_weak_list: print("There is a weak reference") print('The Number of Weak references: ' + str(weakref.getweakrefcount(new_list))) del new_list, new_weak_list #Delete both objects print("The weak reference is: " + str(weak_ref()))
['S', 't', 'r', 'i', 'n', 'g'] ['S', 't', 'r', 'i', 'n', 'g'] The object using proxy: ['S', 't', 'r', 'i', 'n', 'g'] There is a weak reference The Number of Weak references: 2 The weak reference is: None
- Examples of soft references and phantom references?
- PHP References
- Difference Between Strong and Weak Entity
- What are Weak Maps in PHP?
- References in C++
- PHP Spotting References
- PHP Unsetting References
- Difference between Strong Entity and Weak Entity
- How regular expression back references works in Python?
- Explain difference between Strong Entity and Weak Entity
- Create References in Perl
- Circular References in Perl
- PHP Objects and references
- Pointers vs References in C++
- References to Functions in Perl