WeakRef - Weak References

Python AdvancedMemory ManagementFree Lesson

Advertisement

Introduction

The weakref module provides support for weak references - references that do not prevent an object from being garbage collected. This is useful for caches and callbacks.

Weak References

import weakref

class MyClass:
    def __init__(self, value):
        self.value = value

obj = MyClass(42)
ref = weakref.ref(obj)
print(ref().value)  # 42

del obj
print(ref())  # None - object was garbage collected

WeakValueDictionary

import weakref

class Cache:
    def __init__(self):
        self._cache = weakref.WeakValueDictionary()
    
    def get(self, key):
        return self._cache.get(key)
    
    def set(self, key, value):
        self._cache[key] = value

cache = Cache()
cache.set("item", MyClass(100))

WeakKeyDictionary

import weakref

registry = weakref.WeakKeyDictionary()

def register(obj):
    registry[obj] = {"registered": True}

obj = MyClass(1)
register(obj)
print(registry[obj])

WeakSet

import weakref

class Observable:
    def __init__(self):
        self._observers = weakref.WeakSet()
    
    def add_observer(self, observer):
        self._observers.add(observer)

Callbacks and Cleanup

import weakref

class Resource:
    def __init__(self, name):
        self.name = name
    
    def cleanup(self):
        print(f"Cleaning up {self.name}")

def callback(ref):
    print("Object is being deleted")

obj = Resource("test")
ref = weakref.ref(obj, callback)
del obj

Practice Problems

  1. Implement a weak reference cache
  2. Use WeakValueDictionary for memoization
  3. Create an observer pattern with WeakSet
  4. Implement cleanup callbacks
  5. Build a weak reference registry

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement