Python ReferenceError Exception
Example
A ReferenceError occurs if you use a weak reference to an object that no longer exists:
import weakref
class Car:
pass
car = Car()
proxy = weakref.proxy(car)
del car
print(proxy)
Try it Yourself »
Definition and Usage
The ReferenceError exception occurs when you use a weak reference proxy, and the object it refers to no longer exists.
A weak reference (from the weakref module) refers to an object without keeping it alive. In the example, del car removes the only normal reference, so the object is deleted, and the proxy does not work anymore.
Exception Handling
Example
Handling the ReferenceError in a try...except statement:
import weakref
class Car:
pass
car = Car()
proxy = weakref.proxy(car)
del car
try:
print(proxy)
except ReferenceError:
print("The object no longer exists")
Try it Yourself »
Related Pages
Read more about handling errors in our Python Try Except Tutorial.