Weak reference expired
Production Risk
Occurs in caching and observer patterns; prefer weakref.ref() over weakref.proxy() for safer access.
Raised when a weak reference proxy is used to access an object that has already been garbage collected.
- 1Accessing a weakref.proxy() after the referent has been garbage collected
- 2The referent went out of scope and was collected before the proxy was used
Accessing a weakref proxy after the referent is collected.
import weakref class MyObj: pass obj = MyObj() proxy = weakref.proxy(obj) del obj # referent collected print(proxy) # Raises ReferenceError
expected output
ReferenceError: weakly-referenced object no longer exists
Fix
Check if the weak reference is alive before use
WHEN Using weakref.ref() (not proxy)
import weakref
class MyObj: pass
obj = MyObj()
ref = weakref.ref(obj)
# Check before use
if (live_obj := ref()) is not None:
live_obj.do_something()
else:
# Object was collectedWhy this works
weakref.ref() returns None if the referent is collected; weakref.proxy() raises ReferenceError instead.
import weakref class Obj: pass obj = Obj() proxy = weakref.proxy(obj) del obj print(proxy) # ReferenceError: weakly-referenced object no longer exists
try:
result = proxy.value
except ReferenceError:
result = None # object was garbage collectedref = weakref.ref(obj)
live = ref()
if live is not None:
live.do_something()✕ Use weakref.proxy() without a finalizer callback
proxy raises ReferenceError with no warning; use ref() and check for None, or register a finalize() callback.
Python Docs — Built-in Exceptions
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev