3 ms·
One thing that for-else is very useful for is implementing an elegant and easy-to-understand retry mechanism: for _ in range(3): success = do_something
by m4r71n 8y ago
One thing that for-else is very useful for is implementing an elegant and easy-to-understand retry mechanism:
for _ in range(3):
success = do_something()
if success:
break
else:
raise FailedToDoSomething
I generally like this feature of the for loop and it would be a shame if it was removed.
- cup-of-tea 8y agoIndeed I have use this idiom a lot. The alternative is to store a state variable indicating success which isn't very nice.