Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This kind of search can be done a variety of different ways, and is worth abstracting, e.g.:

  def first(candidates, predicate, default):
      try:
          return next(c for c in candidates if predicate(c))
      except StopIteration:
          return default

  deploy_application(first(servers, Server.check_availability, backup_server))


Instead of catching the `StopIteration` exception, you can simply provide a default case to `next` :

    next((c for c in candidates if predicate(c)), default)


Indeed. I was thinking of ways to generalize for the case where a default isn't desired, then decided against introducing that complexity in the example, then forgot that I could re-simplify further.


Great, first() comes part of more_itertools !


`more_itertools` is definitely on my shortlist of things I wish were in the Python standard library. (The list of things I'd like to see cut out, is probably considerably longer. But that's mainly on aesthetic principles; it's probably not creating a significant maintenance burden.)

And yet somehow I keep forgetting about it in the exact moments when it would probably make my life easier.




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: