ReferenceError

A weak proxy does not keep its object alive — once the last strong reference goes, every use of the proxy raises. (Not JavaScript's ReferenceError: an undefined name in Python is NameError.)

InheritsBaseException›Exception›ReferenceError
Runtime exceptionPython 3 (all)Live demo
ReferenceError(*args)
Raised by
attribute access, str(), ==, calls … on a weakref.proxy whose referent is gone
Message
weakly-referenced object no longer exists
Quick fix
keep a strong reference, or use weakref.ref and check for None
Watch out
weakref.proxy(Temp()) is dead immediately

Demo

Live evaluation
watch is a weak proxy to alice's session. The dict entry is the only strong reference. Pick an entry to delete.
Try:
Inputs
dropstralice or bob
Code
import gc, weakref
class Session:
    def __init__(self, user):
        self.user = user
sessions = {'alice': Session('alice'), 'bob': Session('bob')}
watch = weakref.proxy(sessions['alice'])
del sessions['bob']
gc.collect()
watch.user
Result
'alice'

Dropping bob leaves alice's Session referenced by the dict, so the proxy still works. Dropping alice removes the last strong reference; CPython frees the object at once (gc.collect() makes it certain on other implementations too) and watch.user raises. The proxy object itself still exists — it is just empty.

Constructor

NameTypeRequiredDescription
*argsobjectnoThe message; the proxy passes one fixed string.

Attributes

AttributeTypeMeaning
argstupleThe message tuple: ('weakly-referenced object no longer exists',).

Common patterns

weakref.ref + None check
A ref is called to get the object, and returns None when it is gone — no exception to handle.
ref = weakref.ref(session)
...
obj = ref()
if obj is None:
    reconnect()
else:
    obj.ping()
Cache that does not keep things alive
WeakValueDictionary drops entries automatically when the values die — no dead proxies to trip over.
cache = weakref.WeakValueDictionary()
cache[key] = obj
hit = cache.get(key)  # None once obj is gone
Back-reference to a parent
Children point to their parent weakly to avoid reference cycles; the parent owns the children strongly.
class Node:
    def __init__(self, parent=None):
        self.parent = weakref.proxy(parent) if parent else None
        self.children = []

Examples

1. Using a dead proxy
import gc, weakref class Node: pass n = Node() p = weakref.proxy(n) del n gc.collect() p.name
Returns
ReferenceError: weakly-referenced object no longer exists
2. Even str() fails
import gc, weakref class Node: pass n = Node() p = weakref.proxy(n) del n gc.collect() str(p)
Returns
ReferenceError: weakly-referenced object no longer exists
3. A live proxy behaves like the object
import weakref class Node: def __init__(self): self.name = 'root' n = Node() p = weakref.proxy(n) p.name
Returns
'root'
4. weakref.ref returns None instead
import gc, weakref class Node: pass n = Node() r = weakref.ref(n) del n gc.collect() r() is None
Returns
True
5. Proxy to a temporary is dead at once
import weakref class Node: pass p = weakref.proxy(Node()) p.name
Returns
ReferenceError: weakly-referenced object no longer exists
6. Lists and dicts cannot be weakly referenced
import weakref weakref.proxy([1, 2])
Returns
TypeError: cannot create weak reference to 'list' object

Pitfalls

1. Proxy to an object nobody else holds
The proxy is the only reference, and it does not count — the object is freed on the same line it was created.
Only a proxy
import weakref
class Logger:
    level = 'INFO'
log = weakref.proxy(Logger())
log.level
ReferenceError: weakly-referenced object no longer exists
Keep a strong reference
import weakref
class Logger:
    level = 'INFO'
logger = Logger()
log = weakref.proxy(logger)
log.level
'INFO'
2. A proxy is not the object
The proxy forwards attribute access and operators, but it is a separate object: identity checks fail and it cannot be a dict key. weakref.ref gives back the real object.
p is obj
import weakref
class Node:
    pass
n = Node()
p = weakref.proxy(n)
p is n
False
ref() is obj
import weakref
class Node:
    pass
n = Node()
r = weakref.ref(n)
r() is n
True

When to use

Use it
  • Handling a proxy that may outlive its target (observers, parent back-links, caches)
  • Raising it from your own weak-handle type when the target is gone
Reach for something else
  • weakref.proxy when you need to test for liveness → weakref.ref and check for None
  • Weak references as the only reference to something you still need

Notes

CPython impl
Objects/weakrefobject.c — every proxy operation first checks the referent and raises ReferenceError if it is gone
NameError
JavaScript's ReferenceError (undefined variable) is NameError in Python
Weakrefable
Instances of normal classes, functions, sets — not int, str, tuple, list or dict (their subclasses can be)

FAQ

You used a weakref.proxy after the object it pointed to was garbage-collected. A weak reference does not keep an object alive; when the last normal (strong) reference goes, the object is freed and the proxy becomes empty. Keep a strong reference for as long as you need the object, or switch to weakref.ref and check whether ref() returns None.