[Python-ideas] for/except/else syntax

Arnaud Delobelle arnodel at googlemail.com
Wed Oct 7 11:15:48 CEST 2009

2009/10/7 Yuvgoog Greenle <ubershmekel at gmail.com>:
> 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
> For optimization I would suggest the "loop" variable only be
> instantiated if it's referenced. Also, there may be better names for
> "loop", "broke" and "empty".
> Two drawbacks:
> 1. python's in over it's head with reserved words.
> 2. developers might want to use the "loop" variable a mile down from
> the loop which would be ugly but their fault.
> I'm writing a summary of the previous for/else thread and hope that by
> the time I finish that (a week+), someone will invent a readable,
> low-cost syntax (optional but awesome if it can handle all 4:
> break/not break/empty/not empty).

Here's an idea with current syntax (python < 3):

class Loop(object):
    def __init__(self, iterable):
        self.iterable = iterable
    def __iter__(self):
        self.broken = True
        self.empty = True
        for i in self.iterable:
            self.empty = False
            yield i
        self.broken = False

# Example:

for string in 'spam', 'bot', '':
    loop = Loop(string)
    for i in loop:
        if i == 'a':
    print repr(string), ':'
    if loop.broken: print 'broken',
    if loop.empty: print 'empty',

# Output:
'spam' : broken
'bot' :
'' : empty


More information about the Python-ideas mailing list