Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I send a python 'Signal' object from a function, what should the "sender" argument be?

If I send a Signal from a module function (a django view function as it happens), that is not inside a Class, it's not obvious (to me) what the sender should be - if anything? Is sender=None appropriate in this case?

Alternatively, the function is invoked by an HTTP request, which I currently pass in as a separate argument - should I pass that instead?

Option A:

from django.dispatch import Signal
my_signal = Signal(
    providing_args=['my_arg', 'request']
)    

# this is a view function
def do_something(request):
    # ... do useful stuff
    my_signal.send(
        sender=None,
        my_arg="Hello",
        request=request
    )

Option B:

from django.dispatch import Signal
my_signal = Signal(
    providing_args=['my_arg']
)    

# this is a view function
def do_something(request):
    # ... do useful stuff
    my_signal.send(
        sender=request,
        my_arg="Hello",
    )

[UPDATE]

Option A has it. There's nothing useful that the receiver can do with the sender in this case (i.e. it's not an object), so set it to None.

like image 761
Hugo Rodger-Brown Avatar asked Jun 11 '13 11:06

Hugo Rodger-Brown


People also ask

What are the roles of receiver and sender in signals?

receiver – The callback function which will be connected to this signal. See Receiver functions for more information. sender – Specifies a particular sender to receive signals from. See Connecting to signals sent by specific senders for more information.

What is the use of the Post_delete signal in Django?

Django Signals - post_delete()To notify another part of the application after the delete event of an object happens, you can use the post_delete signal.

What kind of signals are there in Django?

There are 3 types of signal. pre_save/post_save: This signal works before/after the method save(). pre_delete/post_delete: This signal works before after delete a model's instance (method delete()) this signal is thrown.

Where is Pre_save signal in Django?

pre_save. This is sent at the beginning of a model's save() method. Arguments sent with this signal: sender.


1 Answers

The django.dispatch.Dispatcher source simply says it should be

"...[t]he sender of the signal. Either a specific object or None."

which then ties in with the receiver via connect(), for which the sender's significance is:

"The sender to which the receiver should respond. Must either be
 of type Signal, or None to receive events from any sender"

which, I admit, isn't particularly clear, but in your case, I would say to use sender=None because there's nothing concrete to hook to, as the request is transient.

like image 170
Steve Jalim Avatar answered Sep 21 '22 16:09

Steve Jalim