2

I am wondering if there is a way to call a method before the object is finally "destroyed" - like some sort of event.

I am using a class and a static method. Since it is not an instantiated object, I cannot use del and modify __del__ on it.

Is the object garbage collected at all if not instantiated?

For example:

class Test:
    @staticmethod
    def say_hello():
        print("Hello")

    def on_destroy(self):
        print("Object was destroyed...")


Test.say_hello()

What I want to achieve is that the method on_destroy will fire after say_hello since I am using a static method.

I tried using __del__ and it is not being called.

Thansk for the help.

Niv
  • 523
  • 1
  • 8
  • 19
  • 2
    Why would you expect `on_destroy()` to be called anywhere in your code? The global name `Test` still exists, and continues to reference your class... If you are assuming the deletion of the name `Test` somehow, then detecting that would require that your class be an instance of a metaclass, that has a `__del__()` method. – jasonharper Mar 19 '23 at 22:20
  • 1
    [This question](https://stackoverflow.com/questions/944336/method-that-gets-called-on-module-deletion-in-python) seems related, might be helpful to you – rpm Mar 19 '23 at 22:23
  • 2
    This feels like an [XY Problem](https://xyproblem.info/). If you describe the original problem you are trying to solve with this we might be able to propose a different solution. – Code-Apprentice Mar 19 '23 at 22:38
  • 1
    In your exampe, you did not create any object, you have just called a class method, so it is totally normal that __del__ was not called, since there no object were created, garbage collection won't be called on just calling class functions – filani Mar 20 '23 at 22:30
  • class objects are not destroyed in cPython - once created they will "live forever". Just use a normal instance with a plain method. Static methods are useless but if you are using your classes as a namespace, (at which point it would make no sense trying to destroy them as well) – jsbueno Apr 12 '23 at 19:57

2 Answers2

0
class Test:
    @staticmethod
    def say_hello():
        print("Hello")

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.on_destroy()

    def on_destroy(self):
        print("Object was destroyed...")

with Test() as t:
    t.say_hello()
Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
-1

It's not guaranteed that the __del__() method will be called after the say_hello() method. So, if you still want the __del__() method to be called after the say_hello() method, you could do like below.

class Test:

class Test:
    @staticmethod
    def say_hello():
        print("Hello")
        t = Test()
        return t
    def __del__(self):
        print("Object was destroyed...")
t = Test.say_hello()
Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268