Re:A Python Guide for the Ages
by globular-toast on Saturday December 25, 2021 @06:14AM
(#29682290)
Instead of avoiding it in production code, it's better to understand that it's the perfect place for a comment. For example:
for ...:
...
else:
# loop ended, no positions found
return ...I used it a bunch in Advent of Code as well. It’s very useful for “search” loops, which should break on finding the target, or do something else if it isn’t found.
Generator return, on the other hand, is something I didn’t even know about (basically, return X in a generator raises StopIteration(X)). I don’t think it’s super useful because even inspecting the arguments to an exception tends to be uncommon practice in most code I’ve seen (more frequently, you just want to report or suppress the error depending on its type). I’m sure there’s a niche use for it somewhere though!
Re:A Python Guide for the Ages
by mixmastamyk on Saturday December 25, 2021 @08:11PM
(#29688720)
Use with a short comment:
for … :
…
else: # break didn’t occur
…
I typically make it even shorter, but this is probably the most readable.
I think the idea is cool (albeit rarely useful), but a different word than "else" for the same functionality would go a long way.