How to remove a list’s element by referencing it by weakref?
import weakref
class Object():
    def __init__(self):
        pass
object = Object()
list = [object]
print(list)
wr = weakref.ref(object)
list.remove(wr)
print(list)
This returns a ValueError: list.remove(x): x not in list.
Advertisement
Answer
You need to call the reference object:
>>> list.remove(wr()) >>> list []
The original object can be retrieved by calling the reference object if the referent is still alive; if the referent is no longer alive, calling the reference object will cause
Noneto be returned.
Btw, don’t use object or list as variable names, those are built-in objects.