3

Is it possible to delete an object by using a weak reference to it?

Basically, I have a weakref object which contains references to all of the objects that are instances of the same class. This is contained in a class attribute which all the objects have, i.e.

weakref_obj = class.instances

I can iterate over the weakref object and return object attributes. I want to delete the object which has a certain _id attribute. I tried:

for item in weakref_obj:
    if item._id == "P":
        del item    

I understand that I could do what I want by using a standard dictionary storing all the objects but this would require more coding, so if I could somehow do it using the weakref object that would be great.

Thanks

EngStan
  • 383
  • 2
  • 13
  • Why didn't your method work? – Eric Conner Mar 04 '16 at 16:01
  • `del` doesn't really delete the item. It only removes the binding of the data to the variable `item`. See http://stackoverflow.com/questions/6146963/when-is-del-useful-in-python – Adi Levin Mar 04 '16 at 16:02
  • Do you want to remove the item from the `class.instances` list, or do you want to destroy the instance? In the latter case, what about other references pointing to that object? – tobias_k Mar 04 '16 at 16:10
  • @tobias_k I want to destroy the instance altogether. I am working on a project which involves accessing objects from a database. To load an object, I want to identify if it already exists in the Python workspace from its unique _id attribute (which I can do using the weakref) and then delete the existing object in python. – EngStan Mar 04 '16 at 16:17
  • I kinda assumed that if I deleted the instance then it would be garbage collected and the weakref would be appropriately updated. Could I obtain the strong reference from the weak one, and then delete it? – EngStan Mar 04 '16 at 16:19

0 Answers0