Is there any way to ensure that when an object is deleted, it is deleted fully from wherever it is?
For example, if you did something like:
A = NewObject()
B = NewObject()
C = NewObject()
List1 = [A,B,C]
List2 = [1,2,3,C]
del A
del List2[3]
and have the objects deleted wherever they are, meaning that List1 would only contain B and that List2 would only contain 1,2,3.
Is there any way that behavior similar to this could be achieved?
You can use weak references in some cases. If you don’t care if
Cremains alive inList2, you can wrap it in a weakref, and when the reference toCexpires from List1, the garbage collector will collect any memory associated with it.Python uses reference counting to decide whether or not an object should be collected, so as long as a reference is held somewhere, you can not fully delete that object. However, if a weakref wraps an object, that reference is not counted. So when the count drops to 0, it’ll be collected at the GC convenience.
Make sure to fully read the documentation though, since there are quite a few caveats associated with weakrefs. Especially the types of objects that are eligible to be used within a weakref.
Edit:
An example –
I highly advise reading the entire documentation on weakrefs. It sounds like you want to build up a node structure, but be able to reference that node structure from a Manager. You would create your nodes as regular objects, but place weakrefs to those objects within the Manager. In that way, when a node is removed, the reference within the Manager simply dies.
A candidate for this would be the
WeakValueDictionarydefined within the weakref module.