[Django]-When receiver has been garbage collected in signal?

3👍

Any Python object may be garbage collected once there are no more references to it. For example, after this view runs…

def example_view(request):
    def my_callback(*args, **kwargs):
        print(args, kwargs)
    some_signal.connect(my_callback)
    return HttpResponse('')

… there is no more reference to my_callback, and the function object stored in it can be garbage-collected at any time. You could do

all_my_callbacks = []
def example_view(request):
    def my_callback(*args, **kwargs):
        print(args, kwargs)
    some_signal.connect(my_callback)
    all_my_callbacks.append(my_callback)
    return HttpResponse('')

Now, there is a reference to the callback function object even after the view is rendered; it is in all_my_callbacks. Alternatively, use a strong reference in the signal with weak=False:

def example_view(request):
    def my_callback(*args, **kwargs):
        print(args, kwargs)
    some_signal.connect(my_callback, weak=False)
    return HttpResponse('')

You can and should avoid all of this hassle by using top-level instead of local functions. Almost universally, this is how your code should look like:

def my_callback(*args, **kwargs):
    print(args, kwargs)

def example_view(request):
    some_signal.connect(my_callback)
    return HttpResponse('')

There is always a reference to such a function, so it is never garbage-collected.

👤phihag

Leave a comment