Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading