From cc63e2f848524b3e5a994a85891f8212158c13b4 Mon Sep 17 00:00:00 2001
From: Jannis Leidel <jannis@leidel.info>
Date: Sun, 1 May 2011 23:55:44 +0200
Subject: [PATCH] Fixed #9015 -- Extended the signal decorator interface by allowing using the Signal.connect method as a decorator.

---
 django/dispatch/dispatcher.py     |   56 ++++++++++++++++++++++--------------
 docs/topics/signals.txt           |   12 ++++++++
 tests/modeltests/signals/tests.py |   21 ++++++++++++-
 3 files changed, 65 insertions(+), 24 deletions(-)

diff --git a/django/dispatch/dispatcher.py b/django/dispatch/dispatcher.py
index ed9da57..305b2ba 100644
--- a/django/dispatch/dispatcher.py
+++ b/django/dispatch/dispatcher.py
@@ -13,17 +13,17 @@ def _make_id(target):
 class Signal(object):
     """
     Base class for all signals
-    
+
     Internal attributes:
-    
+
         receivers
             { receriverkey (id) : weakref(receiver) }
     """
-    
+
     def __init__(self, providing_args=None):
         """
         Create a new signal.
-        
+
         providing_args
             A list of the arguments this signal can pass along in a send() call.
         """
@@ -33,12 +33,12 @@ class Signal(object):
         self.providing_args = set(providing_args)
         self.lock = threading.Lock()
 
-    def connect(self, receiver, sender=None, weak=True, dispatch_uid=None):
+    def connect(self, receiver=None, *args, **kwargs):
         """
         Connect receiver to sender for signal.
-    
+
         Arguments:
-        
+
             receiver
                 A function or an instance method which is to receive signals.
                 Receivers must be hashable objects.
@@ -46,7 +46,7 @@ class Signal(object):
                 If weak is True, then receiver must be weak-referencable (more
                 precisely saferef.safeRef() must be able to create a reference
                 to the receiver).
-        
+
                 Receivers must be able to accept keyword arguments.
 
                 If receivers have a dispatch_uid attribute, the receiver will
@@ -62,19 +62,31 @@ class Signal(object):
                 module will attempt to use weak references to the receiver
                 objects. If this parameter is false, then strong references will
                 be used.
-        
+
             dispatch_uid
                 An identifier used to uniquely identify a particular instance of
                 a receiver. This will usually be a string, though it may be
                 anything hashable.
         """
+        # ``connect`` is being called with a function.
+        if receiver:
+            self._connect(receiver, *args, **kwargs)
+            # Return the receiver, if being used for decoration.
+            return receiver
+        def wrapper(receiver):
+            self._connect(receiver, *args, **kwargs)
+            return receiver
+        # Return this wrapper so that it can be used to decorate a function.
+        return wrapper
+
+    def _connect(self, receiver, sender=None, weak=True, dispatch_uid=None):
         from django.conf import settings
-        
+
         # If DEBUG is on, check that we got a good receiver
         if settings.DEBUG:
             import inspect
             assert callable(receiver), "Signal receivers must be callable."
-            
+
             # Check for **kwargs
             # Not all callables are inspectable with getargspec, so we'll
             # try a couple different ways but in the end fall back on assuming
@@ -90,7 +102,7 @@ class Signal(object):
             if argspec:
                 assert argspec[2] is not None, \
                     "Signal receivers must accept keyword arguments (**kwargs)."
-        
+
         if dispatch_uid:
             lookup_key = (dispatch_uid, _make_id(sender))
         else:
@@ -115,19 +127,19 @@ class Signal(object):
 
         If weak references are used, disconnect need not be called. The receiver
         will be remove from dispatch automatically.
-    
+
         Arguments:
-        
+
             receiver
                 The registered receiver to disconnect. May be none if
                 dispatch_uid is specified.
-            
+
             sender
                 The registered sender to disconnect
-            
+
             weak
                 The weakref state to disconnect
-            
+
             dispatch_uid
                 the unique identifier of the receiver to disconnect
         """
@@ -135,7 +147,7 @@ class Signal(object):
             lookup_key = (dispatch_uid, _make_id(sender))
         else:
             lookup_key = (_make_id(receiver), _make_id(sender))
-        
+
         self.lock.acquire()
         try:
             for index in xrange(len(self.receivers)):
@@ -155,10 +167,10 @@ class Signal(object):
         receivers called if a raises an error.
 
         Arguments:
-        
+
             sender
                 The sender of the signal Either a specific object or None.
-    
+
             named
                 Named arguments which will be passed to receivers.
 
@@ -178,7 +190,7 @@ class Signal(object):
         Send signal from sender to all connected receivers catching errors.
 
         Arguments:
-        
+
             sender
                 The sender of the signal. Can be any python object (normally one
                 registered with a connect if you actually want something to
@@ -265,6 +277,6 @@ def receiver(signal, **kwargs):
 
     """
     def _decorator(func):
-        signal.connect(func, **kwargs)
+        signal._connect(func, **kwargs)
         return func
     return _decorator
diff --git a/docs/topics/signals.txt b/docs/topics/signals.txt
index 64ce202..00f9b0a 100644
--- a/docs/topics/signals.txt
+++ b/docs/topics/signals.txt
@@ -133,6 +133,18 @@ Now, our ``my_callback`` function will be called each time a request finishes.
 
 The ``receiver`` decorator was added in Django 1.3.
 
+.. versionadded:: 1.4
+
+Optionally you can use the signal as a decorator itself::
+
+.. code-block:: python
+
+    from django.core.signals import request_finished
+
+    @request_finished.connect
+    def my_callback(sender, **kwargs):
+        print "Request finished!"
+
 .. admonition:: Where should this code live?
 
     You can put signal handling and registration code anywhere you like.
diff --git a/tests/modeltests/signals/tests.py b/tests/modeltests/signals/tests.py
index 9b8bce0..e097e1e 100644
--- a/tests/modeltests/signals/tests.py
+++ b/tests/modeltests/signals/tests.py
@@ -60,10 +60,18 @@ class SignalTests(TestCase):
 
         # throw a decorator syntax receiver into the mix
         @receiver(signals.pre_save)
-        def pre_save_decorator_test(signal, sender, instance, **kwargs):
+        def pre_save_receiver_decorator_test(signal, sender, instance, **kwargs):
             data.append(instance)
 
         @receiver(signals.pre_save, sender=Car)
+        def pre_save_receiver_decorator_sender_test(signal, sender, instance, **kwargs):
+            data.append(instance)
+
+        @signals.pre_save.connect
+        def pre_save_decorator_test(signal, sender, instance, **kwargs):
+            data.append(instance)
+
+        @signals.pre_save.connect(sender=Car)
         def pre_save_decorator_sender_test(signal, sender, instance, **kwargs):
             data.append(instance)
 
@@ -73,6 +81,7 @@ class SignalTests(TestCase):
         self.assertEqual(data, [
             (p1, False),
             p1,
+            p1,
             (p1, True, False),
         ])
         data[:] = []
@@ -82,17 +91,20 @@ class SignalTests(TestCase):
         self.assertEqual(data, [
             (p1, False),
             p1,
+            p1,
             (p1, False, False),
         ])
         data[:] = []
 
         # Car signal (sender defined)
-        c1 = Car(make="Volkswagon", model="Passat")
+        c1 = Car(make="Volkswagen", model="Passat")
         c1.save()
         self.assertEqual(data, [
             (c1, False),
             c1,
             c1,
+            c1,
+            c1,
             (c1, True, False),
         ])
         data[:] = []
@@ -102,6 +114,7 @@ class SignalTests(TestCase):
         self.assertEqual(data, [
             (p1, True),
             p1,
+            p1,
             (p1, False, True),
         ])
         data[:] = []
@@ -119,6 +132,7 @@ class SignalTests(TestCase):
         self.assertEqual(data, [
             (p2, False),
             p2,
+            p2,
             (p2, True, False),
         ])
         data[:] = []
@@ -128,6 +142,7 @@ class SignalTests(TestCase):
         self.assertEqual(data, [
             (p2, False),
             p2,
+            p2,
             (p2, True, False),
         ])
         data[:] = []
@@ -151,6 +166,8 @@ class SignalTests(TestCase):
         signals.pre_save.disconnect(pre_save_test)
         signals.pre_save.disconnect(pre_save_decorator_test)
         signals.pre_save.disconnect(pre_save_decorator_sender_test, sender=Car)
+        signals.pre_save.disconnect(pre_save_receiver_decorator_test)
+        signals.pre_save.disconnect(pre_save_receiver_decorator_sender_test, sender=Car)
 
         # Check that all our signals got disconnected properly.
         post_signals = (
-- 
1.7.4.1

