pythongarbage-collectionmetaclass

Executing code on class (metaclass instance) destruction in python


We have some API that should be shut down (e.g. api.shutdown()) just once per python process and specific only to a particular class (e.g. ControllerA) from a hierarchy of controllers (e.g. Controller inherited by ControllerA, ..., ControllerZ). Can I add a "destructor logic" in python in some reasonable way when destroying the class itself and not just any of its instances? I understand that in Python classes are not explicitly destroyed in the same way as objects but rather garbage collected when there are no existing references to them but perhaps there is some way to achieve the above effect? What I want is to perform the api.shutdown() call once for all instances but not explicitly as it should not be done for instances of ControllerB ..., ControllerZ. Could using metaclasses or something like metaclass destructors achieve anything like it?


Solution

  • You could use a shutdown hook with atexit. Inside the class definition, add the appropriate function for atexit.

    However, note that it is hard to design your software around when such "cleanup" methods, like atexit or __del__, will be called.

    It can be a better design to have an explicit lifecycle in your application, so that at shutdown, a list of registered callback functions is called.