[Python-ideas] for/else statements considered harmful

Alice Bevan–McGregor alice at gothcandy.com
Thu Jun 7 15:06:38 CEST 2012


So the subject of the thread seems to hold true.  Average developers 
are confused by the current semantic (a problem that needs more than 
abstract p-code to correct) to the point of actively avoiding use of 
the structure.

I agree, however, that breaking all existing code is probably bad.  ;)

On 2012-06-07 00:53:22 +0000, Nick Coghlan said:
>     for x in range(20):
>         if x > 10:
>             break
>     except break:
>         # Bailed out early
>     else:
>         # Reached the end of the loop

Seems a not insignifigant number of readers got fixated on the 
alternate keyword for the current behaviour of else (finally in my 
example) and ignored or misinterpreted the -really important part- of 
being able to detect if the loop was skipped (no iterations performed; 
else in my example).

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!

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!

empty woud be a good keyword to preserve the existing meaning of else, 
but I'm pretty sure that's a fairly common variable name.  :/

	— Alice.





More information about the Python-ideas mailing list