From 6fccd9350e1844157cd57ac2820d9746a9bcc656 Mon Sep 17 00:00:00 2001 From: Forrest Voight Date: Thu, 18 Oct 2012 23:09:29 -0400 Subject: [PATCH 1/1] added util.variable.Event.watch_weakref for code reuse --- p2pool/util/forest.py | 4 +--- p2pool/util/variable.py | 5 +++++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/p2pool/util/forest.py b/p2pool/util/forest.py index 245e909..5114938 100644 --- a/p2pool/util/forest.py +++ b/p2pool/util/forest.py @@ -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 diff --git a/p2pool/util/variable.py b/p2pool/util/variable.py index f9af6db..0050b0d 100644 --- a/p2pool/util/variable.py +++ b/p2pool/util/variable.py @@ -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 -- 1.7.1