[Python-ideas] for/except/else syntax

MRAB python at mrabarnett.plus.com
Wed Oct 7 19:27:22 CEST 2009


Yuvgoog Greenle wrote:
> I don't like your "except" and "else" only because it's not obvious
> when they execute.
> 
> btw your example breaks the current "for..else" search idiom. C,
> suite_if_loop_is_not_broken, should be labelled
> suite_if_loop_is_not_broken_and_not_empty in your example code.
> 
> As I understand it, pythoneers need a way to know what happened with a
> previous loop. Did it break? Did it execute at all? The answer to both
> questions is either True or False and developers need these answers
> only after the loop finished. If python wasn't in over it's head with
> reserved words I would suggest adding "loop":
> 
> for i in SEQ:
>     A
> if not loop.broke:
>     C # suite_if_loop_is_not_broken
> elif loop.empty:
>     B  # suite_if_loop_body_is_not_executed
> 
[snip]
Perhaps:

for i in SEQ:
     A
elif not break:
     C # suite_if_loop_is_not_broken
elif pass:
     B  # suite_if_loop_body_is_not_executed

or:

for i in SEQ:
     A
elif pass:
     B  # suite_if_loop_body_is_not_executed
else:
     C # suite_if_loop_is_not_broken

The first possibility suggests that you could test whether there _was_ a
break and well as whether there wasn't:

for item in item_list:
     if item == desired_item:
         break
elif break:
     print "Found the item"
elif pass:
     print "No items"
else: # or elif not break
     print "Didn't find the item"

This would cause a problem in that "else" wouldn't be the default for
when no elif matched, but would always mean "elif not break"! (Unless it 
defaulted to "elif not break" if it occurred alone.)



More information about the Python-ideas mailing list