Reputation: 11
I have a custom python class
object added to a list upon instantiation.
I would like for the python class
object to remove itself from the list and remove itself from any memory running on the ram or I'm basically looking for a destructor for the class
object and a method to remove the instance from the python structure. I'm not tied to using a list and am open to suggestions about what might be a better container, or any other suggestions on coding style.
Bad pseudocode example of what I'm essentially going for:
mylist=[]
class myclass:
def __init__(self,val):
self.v=val
print(self.v)
mylist.append(self)
# The following is what I'm looking for
__superdestructor__(self):
mylist.pop(self)
memory.remove(self)
Upvotes: 1
Views: 118
Reputation: 18846
Garbage-collection in Python is somewhat complex, but practically, objects become a candidate when there are no more references to them!
Instead of having the object remove itself from the list, have the caller do it - if this is not directly possible, provide an intermediate class which hosts the collection and does whatever cleanup is needed
class MyBigClass():
...
class BigClassHolder():
def __init__(self):
self.container = list() # put your objects in here
... # some getting method
return container.pop() # only reference is now with the caller
Do also consider a collections.deque
over a list for thread safety and other good properties!
Do also note that there are other Python implementations (you are likely using CPython as referenced in the first link) with their own garbage collectors, but I believe removing all the references to an object should eventually result in its removal from memory.
Upvotes: 1