Could overriding Python destructor (__del__) cause memory leaks?

Viewed 297

I have a script where I create an object over a cloud using API and want to delete it over some occasions, at the end of the script.

class ObjCreator():
   def __init__(self, keep_object: bool):
      self.keep_object = keep_object
      print("init")
   
   def create_object(self):
      print("Created object using API")

   def delete_object(self):
      print("Deleting object using API")

   def __del__(self):
      print("Deleting object using API only if keep_object is False")
      if not self.keep_object:
         self.delete_object()

I've seen some memory leaks over Python programs, so obviously the GC isn't prefect (i.e., uncollectable objects).

My fear is that overriding the del function would cause a memory leak. Is that possible? If so, do you have any suggestion to a different, elegant solution?

1 Answers

Your intuition is right, overriding the __del__ method means that the base class's __del__ method is not automatically called anymore (although I don't think a memory leak is likely here). In fact the documentation explicitly mentions this:

If a base class has a __del__() method, the derived class’s __del__() method, if any, must explicitly call it to ensure proper deletion of the base class part of the instance.

A code example for this from the CPython repo:

    def __del__(self):
        # ... your cleanup code here ...
        super().__del__()  # call to base class
Related