Design thought for callbacks

Marko Rauhamaa marko at pacujo.net
Sat Feb 21 11:03:50 EST 2015


Chris Angelico <rosuav at gmail.com>:

> On Sat, Feb 21, 2015 at 1:44 PM, Cem Karan <cfkaran2 at gmail.com> wrote:

>> In order to inform users that certain bits of state have changed, I
>> require them to register a callback with my code. The problem is that
>> when I store these callbacks, it naturally creates a strong reference
>> to the objects, which means that if they are deleted without
>> unregistering themselves first, my code will keep the callbacks
>> alive. Since this could lead to really weird and nasty situations,
>> [...]
>
> No, it's not. I would advise using strong references - if the callback
> is a closure, for instance, you need to hang onto it, because there
> are unlikely to be any other references to it. If I register a
> callback with you, I expect it to be called; I expect, in fact, that
> that *will* keep my object alive.

I use callbacks all the time but haven't had any problems with strong
references.

I am careful to move my objects to a zombie state after they're done so
they can absorb any potential loose callbacks that are lingering in the
system.


Marko



More information about the Python-list mailing list