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.)
Demo
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
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
| Name | Type | Required | Description |
|---|---|---|---|
| *args | object | no | The message; the proxy passes one fixed string. |
Attributes
| Attribute | Type | Meaning |
|---|---|---|
| args | tuple | The message tuple: ('weakly-referenced object no longer exists',). |
Common patterns
ref = weakref.ref(session) ... obj = ref() if obj is None: reconnect() else: obj.ping()
cache = weakref.WeakValueDictionary() cache[key] = obj hit = cache.get(key) # None once obj is gone
class Node: def __init__(self, parent=None): self.parent = weakref.proxy(parent) if parent else None self.children = []
Examples
Pitfalls
import weakref class Logger: level = 'INFO' log = weakref.proxy(Logger()) log.level
import weakref class Logger: level = 'INFO' logger = Logger() log = weakref.proxy(logger) log.level
import weakref class Node: pass n = Node() p = weakref.proxy(n) p is n
import weakref class Node: pass n = Node() r = weakref.ref(n) r() is n
When to use
- 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
- 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
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.