added util.variable.Event.watch_weakref for code reuse
authorForrest Voight <forrest@forre.st>
Fri, 19 Oct 2012 03:09:29 +0000 (23:09 -0400)
committerForrest Voight <forrest@forre.st>
Sat, 20 Oct 2012 20:00:09 +0000 (16:00 -0400)
p2pool/util/forest.py
p2pool/util/variable.py

index 245e909..5114938 100644 (file)
@@ -3,7 +3,6 @@ forest data structure
 '''
 
 import itertools
-import weakref
 
 from p2pool.util import skiplist, variable
 
@@ -13,8 +12,7 @@ class TrackerSkipList(skiplist.SkipList):
         skiplist.SkipList.__init__(self)
         self.tracker = tracker
         
-        self_ref = weakref.ref(self, lambda _: tracker.removed.unwatch(watch_id))
-        watch_id = self.tracker.removed.watch(lambda item: self_ref().forget_item(item.hash))
+        self.tracker.removed.watch_weakref(self, lambda self, item: self.forget_item(item.hash))
     
     def previous(self, element):
         return self.tracker._delta_type.from_element(self.tracker.items[element]).tail
index f9af6db..0050b0d 100644 (file)
@@ -1,4 +1,5 @@
 import itertools
+import weakref
 
 from twisted.internet import defer, reactor
 from twisted.python import failure, log
@@ -13,6 +14,10 @@ class Event(object):
     def run_and_watch(self, func):
         func()
         return self.watch(func)
+    def watch_weakref(self, obj, func):
+        # func must not contain a reference to obj!
+        watch_id = self.watch(lambda *args: func(obj_ref(), *args))
+        obj_ref = weakref.ref(obj, lambda _: self.unwatch(watch_id))
     def watch(self, func):
         id = self.id_generator.next()
         self.observers[id] = func