def testIsalive(self): # Test with a function. f = lambda x: x m = ref(f) self.assertEqual(m.isalive(), True) del f self.assertEqual(m.isalive(), False) # Test with a method. c = TestClass() m = ref(c.callback) self.assertEqual(m.isalive(), True) del c self.assertEqual(m.isalive(), False)
def testGetFunction(self): # Test with a function. f = lambda x: x m = ref(f) self.assertEqual(m.get_function(), f) del f self.assertEqual(m.get_function(), None) # Test with a method. c = TestClass() m = ref(c.callback) self.assertEqual(m.get_function(), c.callback) del c self.assertEqual(m.get_function(), None)
def listen(self, callback, *args, **kwargs): """ Like L{connect()}, but uses a weak reference instead of a normal reference. The signal is automatically disconnected as soon as the handler is garbage collected. @note: Storing signal handlers as weak references means that if your handler is a local function, it may be garbage collected. To prevent this, use L{connect()} instead. @type callback: object @param callback: The callback function. @type args: tuple @param args: Optional arguments passed to the callback. @type kwargs: dict @param kwargs: Optional keyword arguments passed to the callback. @rtype: L{Exscript.util.weakmethod.WeakMethod} @return: The newly created weak reference to the callback. """ if self.lock is None: self.lock = Lock() with self.lock: if self.is_connected(callback): raise AttributeError('callback is already connected') if self.weak_subscribers is None: self.weak_subscribers = [] ref = weakmethod.ref(callback, self._try_disconnect) self.weak_subscribers.append((ref, args, kwargs)) return ref
def testCall(self): # Test with a function. def function(data, *args, **kwargs): data['args'] = args data['kwargs'] = kwargs d = {} f = ref(function) f(d, 'one', two=True) self.assertEqual(d, {'args': ('one',), 'kwargs': {'two': True}}) del function # Test with a method. d = {} c = TestClass() m = ref(c.callback) m('one', two=True) self.assertEqual(c.args, ('one',)) self.assertEqual(c.kwargs, {'two': True}) del c self.assertRaises(DeadMethodCalled, m)