Skip to content
Advertisement

How to remove an element from a list, referencing it by weakref?

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 None to be returned.

https://docs.python.org/3/library/weakref.html#weakref.ref

Btw, don’t use object or list as variable names, those are built-in objects.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement