destructor - Not able to find the point of object destruction in python -


before jump suggestions , let me write poc code similar case:

class x:     _instance=0     def _new__():         if cls._instance:             #instance instantiated , return same instance              return cls._instance         cls._instance=initialize_instance()         return cls._instance 

now library . client code works like:

var = x() # operations on var . . . #end of program 

the problem facing when client code ends , function in library must executed (for cleanup purposes) . have tried close() , __del__() , both don't control when client program ends. ideally think should because instance destroyed. there other way can achieve without adding code client side? client make 1 call handle , let library deal everything.

you haven't removed references x, because still have cls._instance reference. that's why del isn't getting called.

you can wrap client object in context manager, , call whatever need call cleanup on exit method:

class wrapper:     has_been_wrapped = false      # use has_been_wrapped , is_first_instance determine when     # last reference x gone.     def __init__(self, *args, **kwargs):         if not self.has_been_wrapped:             self.is_first_instance = true             self.has_been_wrapped = true         else:             self.is_first_instance = false         self.var = x(*args, **kwargs)     def __enter__(self):         return self.var     def __exit__(self):         if is_first_instance:                         # whatever need cleanup self.var here 

and anywhere use x, use this:

with wrapper() var:     # have instance of x      # cleaned when statement ends. 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -