python destructor not getting called -


i have large script found out lot of connections machine left open , reason 1 of class destructor never getting called.

below simplified version of script manifesting issue. tiered searching around , found out because of gc , weakref in case no help.

2 cases can see destructor getting called are

  1. if call b_class object without passing a_class function

    self.b = b_class("aa") 
  2. i call make b_class objects not global i.e not use self

    b = b_class("aa",self.myprint) b.do_something() 

both of these cases cause further issues case. last resort close/del objects @ end myself don't want go way.

can suggest better way out of , me understand issue? in advance.

import weakref   class a_class:      def __init__(self,debug_level=1,version=none):         self.b = b_class("aa",self.myprint)         self.b.do_something()      def myprint(self, text):         print text  class b_class:      def __init__(self,ip,printfunc=none):         self.ip=ip         self.new_ip =ip         #self.printfunc = printfunc         self.printfunc = weakref.ref(printfunc)()     def __del__(self):         print("##b_class destructor called##")      def do_something(self,timeout=120):         self.myprint("b_class ip=%s!!!" % self.new_ip)      def myprint(self,text):         if self.printfunc:             print ("extenalfunc:%s" %text)         else:             print ("justprint:%s" %text)  def _main():   = a_class()  if __name__ == '__main__':     _main() 

you're not using weakref.ref object properly. you're calling after created, returns referred-to object (the function passed in printref).

normally, you'd want save weak reference , call when you're going use reffered-to object (e.g. in myprint). however, won't work bound method self.myprint you're getting passed in printfunc, since bound method object doesn't have other references (every access method creates new object).

if you're using python 3.4 or later , know object passed in bound method, can use weakmethod class, rather regular ref. if you're not sure kind of callable you're going get, might need type checking see if weakmethod required or not.


Comments