Behavior of the for-else construct

Cameron Simpson cs at cskk.id.au
Sat Mar 5 17:18:23 EST 2022


On 05Mar2022 17:48, Avi Gross <avigross at verizon.net> wrote:
>Since we still seem to be dreaming, I wonder when someone will suggest using some variation of the new match statement.

Ugh :-)
But...
What if break were implemented with an exception, like StopIteration but 
for interruption instead of stop? And for-loops were an implied 
try/except:
 for ...
 except BrokenIteration: # <-- implied
 pass
and you could go:
 for ...
 except BrokenIteration:
 ... a break occurred
 else:
 ... a break did not occur
and, indeed,
 for ...
 except BrokenIteration:
 ... a break occurred
 except StopIteration as stopped:
 print("I did", stopped.count, "iterations")
 else:
 # not reached because of the "except StopIteration" above
 ... a break did not occur
if we wanted to cover off the count iterations wish item.
Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /