for: else: - any practical uses for the else clause?
Paul Rubin
http
Sat Sep 30 04:52:03 EDT 2006
Peter Otten <__peter__ at web.de> writes:
> I like
>
> def blocks_til_mark(stack):
> for block in stack:
> if block.is_marked():
> return
> yield block
> raise SomeError
> height = sum(block.height for block in blocks_til_mark(stack))
Oh my, I realize now that I mis-read the original, and my examples
were all wrong. Shows how the explicit loop isn't necessarily so
clear ;-). Note that unlike the original, the loop above fails to set
height = 0 in the case where the exception gets raise.
I'd maybe just scan the stack twice. The rescan is needed only if
there can be blocks with height <= 0. Otherwise, you can just raise
SomeError if height == 0:
height = sum(b.height for b in
itertools.takewhile(lambda: not block.is_marked(), stack))
if height == 0 and True not in (b.is_marked() for b in stack):
raise SomeError
More information about the Python-list
mailing list