Design thought for callbacks

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Feb 22 08:45:49 EST 2015


Chris Angelico wrote:

> On Sun, Feb 22, 2015 at 9:32 PM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> Why? Do you expect that the Python garbage collector special cases
>> callbacks to keep them alive even when there are no references to them?
>> How would it distinguish a callback from some other function?
> 
> No no no. It's the other way around. _Something_ has to be doing those
> callbacks, and it's that _something_ that should be keeping them
> alive. The fact that it's a registered callback should itself *be* a
> reference (and not a weak reference), and should keep it alive.

That's much more reasonable than what you said earlier:

    it seems wrong to have to stash a thing in a bucket in order
    to keep its callbacks alive. I expect the callbacks themselves to
    keep it alive.


So yes. If I bind a callback to a button, say, or a listener, then the
button (or listener) keeps the callback alive, *not* the callback keeping
the button or listener alive.

But if there are no references to the button, or the listener, then it will
be garbage-collected, which will free the references to the callback and
allow it to be garbage-collected as well (if there are no further
references to it).



-- 
Steven




More information about the Python-list mailing list