Cannot unregister functions from atexit in python 2.7 -


first, wrote recording class flush method:

class recorder     def __init__(self, buffer_size, path):         self._big_buffer = np.array(*buffer_size)         self._path = path     def push(self, data):         # insert in self._big_buffer         # if self._big_buffer full:         #     self._flush()     def flush(self):         # write buffer disk (self._path) 

then, wanted flush @ exit: when manually stopped, crashed or whatever reason.

so used:

def __init__(self):     (...)     atexit.register(self.flush) 

and worked pretty well.

but now, want record, stop recording, record again, multiple times, different buffer size , different path. have discard, instanciate several recorder. kind of works, older recorder's memory (containing fat self._big_buffer̀) not freed since it's retained atexit. when explicitly call del. can't atexit.unregister(self._flush) since it's python 3 only.

i prefer not reuse existing instances, discarding older instances , create new ones.

how handle such case?

you can try using weak reference atexit handler, object won't retained if deleted elsewhere:

import atexit import weakref  class callablemethodweakref:     def __init__(self, object, method_name):         self.object_ref = weakref.ref(object)         self.method_name = method_name     def __call__(self):         object = self.object_ref()         if object:             getattr(object, self.method_name)()  class recorder:     def __init__(self, *args):         atexit.register(callablemethodweakref(self, 'flush'))      def flush(self):         print 'flushing' 

the method passed string in order avoid lot of problems bound method weak references, if find disturbing can use boundmethodweakref implementation one: http://code.activestate.com/recipes/578298-bound-method-weakref/


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

c# - two queries in same method -