1

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)
martineau
  • 119,623
  • 25
  • 170
  • 301
randomUser
  • 11
  • 4
  • 1
    Please don't use pseudo-code. Just use regular code. – quamrana Feb 12 '21 at 21:08
  • 2
    Python doesn't have destructors. And more importantly, Python *is a memory managed languages*, it doesn't expose any way to explicitly allocate and deallocate memory. Objects will be available for garbage collections when they are no longer reachable (no longer referenced, or only referenced in a circular reference). In CPython, reference counting is the main garbage collection strategy, and objects are reclaimed as soon as their reference count reaches 0. Fundamentally, you are coming at python with the wrong ideas, likely from a lower-level langauge like C++ – juanpa.arrivillaga Feb 12 '21 at 21:12
  • I cant use regular code if I don't know anything like 'superdestructor' besides it compiles before my comment in code – randomUser Feb 12 '21 at 21:13
  • You say you are looking for `__superdestructor__`, a dunder method, what is your *expectation* for when this hook would be utilized? e.g. the `__add__` hook is utilized by the `+` operator. – juanpa.arrivillaga Feb 12 '21 at 21:13
  • The list itself holds a reference to the object, so you need to remove it *first* before the object can actually be garbage-collected. You might look into keeping a list of *weak* references, though I would verify that you really need to do something like this first. Typically, you don't worry about these details. – chepner Feb 12 '21 at 21:14
  • yeah @juanpa.arrivillaga you're right and thank you for the info. Do you know anything pythonic ways that might be close to my goal? yes actually, there is another dunder where "if other.val+self.val=0, then self.superdesctruc()" is what I'm going for – randomUser Feb 12 '21 at 21:14
  • 4
    Fundamentally, the object shouldn't be removing itself from a container, that sort of design is very unwieldy. Instead, you should be writing a class that *manages this relationship*. e.g. `class CollectionOfMyClass` which has some internal list – juanpa.arrivillaga Feb 12 '21 at 21:15
  • @randomUser fundamentally, your goal *doesn't make sense* in Python. This to me seems like a classic example of the [X-Y problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem), that is, you are describing some *solution* to the actual problem you have, instead, you should tell us about the actual problem – juanpa.arrivillaga Feb 12 '21 at 21:17
  • 1
    thank you @juanpa.arrivillaga and chepner for your suggestions – randomUser Feb 12 '21 at 21:17

1 Answers1

1

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.

ti7
  • 16,375
  • 6
  • 40
  • 68
  • 1
    Mmmm garbage collection is *usually* pretty straightforward in CPython: reference counting, the auxilliary cyclic garbage collector is a bit more complex, but is often not relevant. Nothing really like the complex garbage collection of say, the JVM. But yes, I agree with your suggestion of how to handle this. – juanpa.arrivillaga Feb 12 '21 at 21:18
  • @juanpa.arrivillaga indeed! However, there's always been a little (rather healthy) confusion around when the Python process' actually gives up memory, which is complex! Though this seems easier to reason about with newer (not decade-old) versions https://stackoverflow.com/questions/15455048/releasing-memory-in-python – ti7 Feb 12 '21 at 21:23
  • @ti7 ah, totally. Yeah, Python has a privately managed heap, and it's certainly the sort of thing that I would consider complex. – juanpa.arrivillaga Feb 12 '21 at 21:24