A quirk/gotcha of for i, x in enumerate(seq) when seq is empty

Rick Johnson rantingrickjohnson at gmail.com
Tue Feb 28 23:56:10 CET 2012


On Feb 24, 8:54 am, Steven D'Aprano <steve
+comp.lang.pyt... at pearwood.info> wrote:

> for...else is a very useful construct, but the name is misleading. It
> took me a long time to stop thinking that the else clause executes when
> the for loop was empty.

Agreed. This is a major stumbling block for neophytes.

> In Python 4000, I think for loops should be spelled:
>
> for name in iterable:
>     # for block
> then:
>     # only if not exited with break
> else:
>     # only if iterable is empty
>
> and likewise for while loops.

I like this syntax better than the current syntax, however, it is
STILL far too confusing!

> for name in iterable:
>     # for block

this part is okay

> then:
>     # only if not exited with break

I only know how the "then" clause works if you include that comment
each and every time!

> else:
>     # only if iterable is empty

Again. I need more info before this code becomes intuitive. Too much
guessing is required. Not to mention that the try/except/else suite
treats "else" differently.

try:
   do_this()
except EXCEPTION:
   recover()
else NO_EXCEPTION:
   okay_do_this_also().

for x in iterable:
   do_this()
except EXCEPTION:
   recover()
else NO_EXCEPTION:
   do_this_also()

while LOOPING:
    do_this()
except EXCEPTION:
    break or recover()
else NO_EXCEPTION:
    do_this_also()

In this manner "else" will behave consistently between exception
handling and looping.

But this whole idea of using an else clause is ridiculous anyway
because all you've done is to "break up" the code visually. Not to
mention; breaking the cognitive flow of a reader!

try:
    do_this()
    okay_do_this_also()
    what_the_heck.do_this_too()
except EXCEPTION:
    recover()
finally:
   always_do_this()

Loop syntax can drop the "else" and adopt "then/finally" -- if you
think we even need a finally!?!?

for x in iterable:
   do_this()
except EXCEPTION:
   recover()
then:
    okay_do_this_also()
    what_the_heck.do_this_too()
finally:
   always_do_this()

while LOOPING:
    do_this()
except EXCEPTION:
   recover()
then:
    okay_do_this_also()
    what_the_heck.do_this_too()
finally:
   always_do_this()




More information about the Python-list mailing list