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

Paul Rubin http
Sat Sep 30 10:57:24 CEST 2006

Peter Otten <__peter__ at> writes:
> >      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:

Yeah, that's what I mean about generators not working the right way.

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

I think it's better underneath, but still syntactically ugly, to just
defer the generator creation:

     all_heights = lambda: 
                     (block.height for block in stack if block.is_marked())
     if is_empty(all_heights ()):
         raise SomeError("No marked block")
     height = sum(all_heights ())

Now sum and is_empty see two separate generators, so is_empty is

     def is_empty(gen):
           return True
        except StopIteration:
           return False

More information about the Python-list mailing list