ReferenceError
PythonERRORNotableRuntime ErrorHIGH confidence

Weak reference expired

Production Risk

Occurs in caching and observer patterns; prefer weakref.ref() over weakref.proxy() for safer access.

What this means

Raised when a weak reference proxy is used to access an object that has already been garbage collected.

Why it happens
  1. 1Accessing a weakref.proxy() after the referent has been garbage collected
  2. 2The referent went out of scope and was collected before the proxy was used
How to reproduce

Accessing a weakref proxy after the referent is collected.

trigger — this will error
trigger — this will error
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)

Check if the weak reference is alive before use
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 collected

Why this works

weakref.ref() returns None if the referent is collected; weakref.proxy() raises ReferenceError instead.

Code examples
Triggerpython
import weakref
class Obj: pass
obj = Obj()
proxy = weakref.proxy(obj)
del obj
print(proxy)  # ReferenceError: weakly-referenced object no longer exists
Handle with try/exceptpython
try:
    result = proxy.value
except ReferenceError:
    result = None  # object was garbage collected
Avoid with weakref.ref() checkpython
ref = weakref.ref(obj)
live = ref()
if live is not None:
    live.do_something()
What not to do

Use weakref.proxy() without a finalizer callback

proxy raises ReferenceError with no warning; use ref() and check for None, or register a finalize() callback.

Sources
Official documentation ↗

Python Docs — Built-in Exceptions

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors