"for" with "else"?

Andrew Dalke adalke at mindspring.com
Tue Sep 30 23:31:10 EDT 2003


Stephen Horne:
> I can see the use an application of 'else', of course - if you use
> 'break' to end a loop you may need different cleanup and therefore
> need to skip the standard cleanup. But if this is an issue I'm
> probably already using raise rather than break because it's most
> likely an error rather than a normal case.
>
> My guess is that it probably made a lot more sense before exceptions
> were added to Python.

I don't agree.  Here's an example from my code.  The
Match returns an iterator and all the matches have the
same number of atoms, so I want to get that number
if there are any matches or 0 if there are no atoms.

for mb in mcss.Match(mol):
    # All matches are equally maximal, so pick one
    n = mb.NumAtoms()
    break
else:
    # No hits
    n = 0

This example could be replaced with

n = 0
for mb in mcss.Match(mol):
    n = mbNumAtoms()
    break

But consider binhex.py, which does

for c in data:
    if not x.isspace() and (c<' ' or ord(c) > 0x7f):
        break
else:
    finfo.Type = 'TEXT'

Without else: this is written as

flg = 0
for c in data:
  if not x.isspace() and (c<' ' or ord(c) > 0x7f):
        flg = 1
        break
if not flg:
    finfo.Type = 'TEXT'

which is obviously more cumbersome.  But I don't
see how using exceptions make this any nicer.


Here's an example from _strptime.py

for value in to_convert:
    if value != '':
        break
else:
    return ''
 ... do things with to_convert and return a regexp string

Again, the standard solution without an 'else:' is
to have a flag, which looks uglier.

In my search, I didn't see any examples which were
better done with exceptions -- and since (string) exceptions
existed in the language for a long time (from the start
I would imagine and definitely pre-1.3, which is
about when I started), I find it hard to believe that
your statement reflects what really happened.

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list