[Python-ideas] for/else syntax

Nick Coghlan ncoghlan at gmail.com
Thu Oct 1 12:54:16 CEST 2009


Yuvgoog Greenle wrote:
> On python-dev the subject of for/else statements came up, so I had to
> mention how "ambiguous" the syntax seems to me. By "ambiguous" I meant
> that it's not obvious what should happen in the for/else and while/else
> constructs (the except/else construct is readable and great imo btw).
> 
> Even though it's documented, for me it's a bad construct because it can
> and will always be misinterpreted by a non-trivial amount of people
> seeing it for the first time. It's unreadable and confusing because the
> "else" isn't referring to the "for" it's in reference to the "break".
> The construct is only useful in loops with "break" statements, so in
> pseudo code or human the "else" would have probably been translated to
> "if didn't break".

You need a much better reason than "it might confuse newbies" to justify
breaking working code.

In the primary intended context (search loops) the current terminology
makes perfect sense:

  for obj in iterable:
    if found_it(obj):
      # Found what we were looking for!
      break
  else:
    # It wasn't there :(

Similarly for while loops:

  while self.more_points_to_check():
    if self.found_it():
      # Found the desired point
      break
  else:
    # Exhausted the search space :(

And once people learn the idiom, it is easy to remember (so long as they
learn it properly - i.e. as an easy way to write a search loop with a
separate handler for the "not found" case).

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------



More information about the Python-ideas mailing list