Hacker News new | ask | show | jobs
by 63 1637 days ago
I actually saw someone use that for-else pattern in advent of code earlier this month. I believe the consensus was that it was definitely the perfect choice for the given use case, but neither he nor I would ever dare use it in production because nobody knows about it and it's super unintuitive.

I think the idea is cool (albeit rarely useful), but a different word than "else" for the same functionality would go a long way.

3 comments

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!

Use with a short comment:

    for … :
        …
    else:  # break didn’t occur
        …
I typically make it even shorter, but this is probably the most readable.