for: else: - any practical uses for the else clause?

Peter Otten __peter__ at web.de
Sat Sep 30 10:47:18 CEST 2006


Paul Rubin wrote:

> Sybren Stuvel <sybrenUSE at YOURthirdtower.com.imagination> writes:
>> I must say that the for/else construct is a LOT more readable than the
>> rewritten alternatives.
> 
> They are all pretty ugly.  I prefer the genexp version with a
> hypothetical "is_empty" function:
> 
>      all_heights = (block.height for block in stack if block.is_marked())
>      if is_empty(all_heights):
>         raise SomeError("No marked block")

Such a function would have to rebind the generator:

def check_empty(items):
    items = iter(items)
    try:
        first = items.next()
    except StopIteration:
        return False
    return chain([first], items)

all_heights = check_empty(all_heights)
if not all_heights:
    raise SomeError

>      heights = sum(all_heights)
> 
> Python generators don't really work the right way for this though.

You can make it work, but the result tends to be messy:

from itertools import chain

def raiseiter(exc, *args):
    raise exc(*args)
    yield None # unreachable
def stop():
    raise StopIteration

height = sum(block.height for block in chain(stack, raiseiter(SomeError)) if
    (not block.is_marked()) or stop())

Peter



More information about the Python-list mailing list