Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When receiver has been garbage collected in signal?

Tags:

python

django

I try to use Signal in Django, when I read document about method connect signal, it have weak parameter as following:

weak – Django stores signal handlers as weak references by default. Thus, if your receiver is a local function, it may be garbage collected. To prevent this, pass weak=False when you call the signal’s connect() method.

I don't know when local function has been garbage collected?

like image 258
Peep Peep Peep Avatar asked Sep 21 '25 00:09

Peep Peep Peep


1 Answers

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.

like image 111
phihag Avatar answered Sep 22 '25 16:09

phihag