[Python-ideas] for/else statements considered harmful

Ethan Furman ethan at stoneleaf.us
Thu Jun 7 15:21:24 CEST 2012


Alice Bevan–McGregor wrote:
> Being able to have a block executed if the loop is never entered is 
> vitally important so you can avoid expensive or potentially impossible 
> length checks on the iterator before the loop.  Take this example:
> 
>    sock = lsock.accept()
>    for chunk in iter(partial(sock.recv, 4096), ''):
>        pass # do something with the chunk
>    else:
>        pass # no data recieved before client hangup!

This is, indeed, the usual way I try to use these contructs...


> Using a temporary varable to simulate this is… unfortunate.
> 
>    sock = lsock.accept()
>    has_data = False
>    for chunk in iter(partial(sock.recv, 4096), ''):
>        has_data = True
>        pass # do something with the chunk
> 
>    if not has_data:
>        pass # no data recieved before client hangup!

and this is how I usually work around it.  :(

~Ethan~



More information about the Python-ideas mailing list