[Python-ideas] Control Flow - Never Executed Loop Body

Sjoerd Job Postmus sjoerdjob at sjec.nl
Thu Mar 24 02:54:19 EDT 2016


On Tue, Mar 22, 2016 at 01:20:05PM +0100, Sven R. Kunze wrote:
> Now, that you mention it. This might give birth to a completely
> different idea. What about?
> 
> 
> for item in collection:
>     # do for item
> except EmptyCollection:
>     # do if collection is empty
> except StopIteration:
>     # do after the loop
> 
> Which basically merges try and for?

What worries me about this is that the next question is going to be: Why
not have this on `with` suites, `if` suites, and so on. I've already
seen remarks symmilar to that as replies. Especially because of your
remark 'Which basically merges try and for', which adds to my worries.


Consider the following:

    for item in [0, 1, 2]:
        raise StopIteration
    except StopIteration:
        # do after the loop
        # Also after a `raise` inside the loop body?

>From your statement 'merges try and for', it would seem as you now want
the exception to be caught in this case as well. Now, maybe you did not
intend it as such, and really intended to only catch the exceptions
raised by the iterable itself. But that was not quite clear to begin
with. Because of this (possible) confusion, I'd really suggest slapping
on another keyword to the `for` statement over allowing `except` clauses
with limited use.

Another reason is that

    for item in [0, 1, 2]:
        # do something
    except StopIteration:
        pass

would do exactly the same as the `for` loop without the `except` clause,
(due to the `pass`). Now this does not break the principle of 'one
obvious way to do it', because for Pythonistas with experience, the
`except` is superfluous. But would a novice know? (Assuming he started
not by reading the Python docs, but by working on code written by
another programmer)? Yes, RTFM, but more often you learn by reading
other peoples code.


More information about the Python-ideas mailing list