[Python-3000] else-clause on for-loops

Nick Coghlan ncoghlan at gmail.com
Fri Mar 24 13:12:54 CET 2006


Nicola Larosa wrote:
> Fredrik Lundh:
>> (fwiw, the else statement in Python *always* means the same thing: exe-
>> cute this when the controlling condition has been tested and found false)
> 
> Precisely. And that's why the current behavior is counterintuitive: "no
> loops executed" is a better "false controlling condition" than "a few loops
> executed, but not all", as is the case when using "break".

It actually maps better than one might think - the only thing that's not 
necessarily obvious is that the condition being tested in both the while loop 
and for loop cases is "do I want to run the loop body?". If that's False, we 
execute the else clause and get out of there, just like a normal if statement.

The reason 'break' is special is because it kills the loop without the loop 
condition ever becoming false - so the else clause gets skipped as a result.

Making the criteria "no loops were executed" means that the loop condition now 
has to be tested in two separate places, because the first iteration has to be 
special cased. Defining those semantics is definitely possible, but it really 
isn't very nice.

OTOH, there's a fairly easy alternative for handling arbitrary iterables:

   from itertools import chain

   def checked_iter(iterable):
       "Returns None if the iterable is empty, equivalent iterator otherwise"
       itr = iter(iterable)
       try:
           item = itr.next()
       except StopIteration:
           return None
       return chain((item,), itr)

Used like:

   my_itr = checked_iter(iterable)
   if my_itr is not None:
        # Use it
   else:
       # It was empty

Is it worth sending this to Raymond as an itertools candidate? It's the 
cleanest way I know of to convert code that relies on "bool(container)" to 
handle arbitrary iterators instead, and judging from responses here, it's only 
obvious if you've drunk enough of the iterator Kool-Aid ;)

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-3000 mailing list