Design thought for callbacks

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Feb 22 05:32:06 EST 2015


Chris Angelico wrote:

> On Sun, Feb 22, 2015 at 3:38 PM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> But you are using it. You might not be using it by name, but you are
>> using it via the callback function. What did you expect, that Python
>> should read your mind and somehow intuit that you still care about this
>> socket listener, but not some other socket listener that you are done
>> with?
>>
>> You don't have to bind the listener to a name. Any reference will do. You
>> can dump it in a bucket:
>>
>> bucket_of_stuff = []
>> bucket_of_stuff.append(some_function(a, b, c))
>> bucket_of_stuff.append(make_web_server())
>> bucket_of_stuff.append(socket(23, on_accept=client_connected))
> 
> Sure, and whether it's a name or a list-element reference doesn't
> matter: 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. 

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?

If I stuff a function in a list:

   [len]

would you expect the presence of the function to keep the list alive when
there are no references to the list?

Apart from "But I really, really, REALLY want a magical pony that feeds
itself and never poops and just disappears when I don't want it around!"
wishful-thinking, which I *totally* get, I don't see how you think this is
even possible. Maybe I'm missing something, but it seems to me that what
you're wishing for is impossible.

Perhaps if we had a special "callback" type which was treated as a special
case by the garbage collector. But that opens up a big can of worms: how do
you close/delete objects which are kept alive by the presence of callbacks
if you don't have a reference to either the object or the callback?



-- 
Steven




More information about the Python-list mailing list