Design thought for callbacks

Chris Angelico rosuav at gmail.com
Sat Feb 21 21:11:38 EST 2015


On Sun, Feb 22, 2015 at 1:04 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> Marko Rauhamaa wrote:
>
>> Grant Edwards <invalid at invalid.invalid>:
>>
>>> the polite thing to do is to delete references to it when you're done
>>> with it.
>>
>> I disagree with that recommendation. You should do the natural thing and
>> not care who holds references to who.
>
> I don't understand this. What is "the natural thing" if not to delete
> references to an object when you are done with it? Normally you just let
> things go out of scope, but if that won't happen, you have to take active
> steps, such as calling del or setting the reference to None.

I think the disagreement here is over the interpretation of "done with
it". If you drop all references to a connected socket object, Python
can rightly assume that you're done with the file and want to close
it; but what if you drop all references to a listening socket that's
been configured to call a function whenever someone connects?

def client_connected(sock):
    sock.send("Hello!\r\n")
    # whatever

listener = socket(23, on_accept=client_connected)

What should happen if that main socket isn't bound to a name? In my
opinion, the fact that it's configured for callback mode should mean
that it's kept alive. But it's also understandable to want to treat it
as "done", that it can be disposed of. It seems weird to me that you
should have to have a name somewhere that you'll never use, though.

ChrisA



More information about the Python-list mailing list