3 ms·
This kind of search can be done a variety of different ways, and is worth abstracting, e.g.: def first(candidates, predicate, default): try:
by zahlman 2y ago
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))
- sowhat25 2y agoGreat, first() comes part of more_itertools !
- zahlman 2y ago`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.
- nostoc 2y agoInstead of catching the `StopIteration` exception, you can simply provide a default case to `next` : next((c for c in candidates if predicate(c)), default)
- zahlman 2y agoIndeed. 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.