From 3fcca0e94721a734882389ce473f522d293907e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Anssi=20K=C3=A4=C3=A4ri=C3=A4inen?= Date: Thu, 20 Sep 2012 03:18:19 +0300 Subject: [PATCH] Added a way to check if a signal has listeners --- django/dispatch/dispatcher.py | 3 +++ .../regressiontests/dispatch/tests/test_dispatcher.py | 11 +++++++++++ 2 files changed, 14 insertions(+) diff --git a/django/dispatch/dispatcher.py b/django/dispatch/dispatcher.py index ad7302176e..8d26e58bf4 100644 --- a/django/dispatch/dispatcher.py +++ b/django/dispatch/dispatcher.py @@ -141,6 +141,9 @@ class Signal(object): del self.receivers[index] break + def has_listeners(self, sender=None): + return bool(self._live_receivers(_make_id(sender))) + def send(self, sender, **named): """ Send signal from sender to all connected receivers. diff --git a/tests/regressiontests/dispatch/tests/test_dispatcher.py b/tests/regressiontests/dispatch/tests/test_dispatcher.py index 5f7094d5fa..4e4669d34c 100644 --- a/tests/regressiontests/dispatch/tests/test_dispatcher.py +++ b/tests/regressiontests/dispatch/tests/test_dispatcher.py @@ -126,6 +126,17 @@ class DispatcherTests(unittest.TestCase): a_signal.disconnect(receiver_3) self._testIsClean(a_signal) + def test_has_listeners(self): + self.assertIs(a_signal.has_listeners(), False) + self.assertIs(a_signal.has_listeners(sender=object()), False) + receiver_1 = Callable() + a_signal.connect(receiver_1) + self.assertIs(a_signal.has_listeners(), True) + self.assertIs(a_signal.has_listeners(sender=object()), True) + a_signal.disconnect(receiver_1) + self.assertIs(a_signal.has_listeners(), False) + self.assertIs(a_signal.has_listeners(sender=object()), False) + class ReceiverTestCase(unittest.TestCase): """