How to remove a list’s element by referencing it by weakref?
JavaScript
x
14
14
1
import weakref
2
3
class Object():
4
def __init__(self):
5
pass
6
7
object = Object()
8
list = [object]
9
print(list)
10
11
wr = weakref.ref(object)
12
list.remove(wr)
13
print(list)
14
This returns a ValueError: list.remove(x): x not in list
.
Advertisement
Answer
You need to call the reference object:
JavaScript
1
4
1
>>> list.remove(wr())
2
>>> list
3
[]
4
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
None
to be returned.
Btw, don’t use object
or list
as variable names, those are built-in objects.