[Python-ideas] Nudging beginners towards a more accurate mental model for loop else clauses
MRAB
python at mrabarnett.plus.com
Sat Jun 9 18:49:48 CEST 2012
On 09/06/2012 17:01, Jan Kaliszewski wrote:
> Nick Coghlan dixit (2012-06-08, 19:04):
>
>> for x in iterable:
>> ...
>> except break: # Implicit in the semantics of loops
>> pass
>> else:
>> ...
>>
>> Would it be worth adding the "except break:" clause to the language
>> just to make it crystal clear what is actually going on? I don't think
>> so, but it's still a handy way to explain the semantics while gently
>> steering people away from linking for/else and if/else too closely.
>
> IMHO a better option would be a separate keyword, e.g. 'broken':
>
> for x in iterable:
> ...
> broken:
> ...
> else:
> ...
>
> And not only to make the 'else' more understandable. I found, in
> a few situations, that such a 'broken' clause would be really useful,
> making my code easier to read and maintain. There were some relatively
> complex, parsing-related, code structures...
>
> stopped = False
> for x in iterable:
> ...
> if condition1:
> stopped = True
> break
> ...
> if contition2:
> stopped = True
> break
> ...
> if contition3:
> stopped = True
> break
> ...
> if stopped:
> do_foo()
> else:
> do_bar()
>
[snip]
That can be re-written as:
stopped = True
for x in iterable:
...
if condition1:
break
...
if condition2:
break
...
if condition3:
break
...
else:
stopped = False
if stopped:
do_foo()
else:
do_bar()
More information about the Python-ideas
mailing list