Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django 1.8 - Signals - What's the difference between @receiver decorator and Signal.connect() method?

They appear to do the same thing. Is there a difference in functionality, usage, etc? In what circumstances should one be used over the other?

Thanks

like image 917
StringsOnFire Avatar asked Jul 27 '15 11:07

StringsOnFire


2 Answers

They indeed do exactly the same thing from a functional point of view. There is no reason to prefer the one over the other whatsoever, apart from how the developer wants to organize the code.

EDIT: As per the excellent answer from @knbk, you should use the connect function for specific actions, as for example to pass a list of callback functions.

From the Django documentation on signals:

There are two ways you can connect a receiver to a signal. You can take the manual connect route:

from django.core.signals import request_finished

request_finished.connect(my_callback)

Alternatively, you can use a receiver() decorator:

from django.core.signals import request_finished
from django.dispatch import receiver

@receiver(request_finished)
def my_callback(sender, **kwargs):
    print("Request finished!")
like image 142
Wtower Avatar answered Sep 30 '22 16:09

Wtower


@receiver is a thin wrapper around Signal.connect(). The only difference is that @receiver can accept not just a single signal, but also a list or tuple of signals, and it will connect the function to each of those signals.

If you take a look at the source code, @receiver only calls signal.connect(func) and returns the original function.

like image 20
knbk Avatar answered Sep 30 '22 17:09

knbk