I had a function that returned a random member from several groups in order of preference. It happened something like this:
def get_random_foo_or_bar(): "I'd rather have a foo than a bar." if there_are_foos(): return get_random_foo() if there_are_bars(): return get_random_bar() raise IndexError, "No foos, no bars"
However, the first thing get_random_foo really checks is that foos exist and raise an IndexError if not, so there_are_foos is redundant. In addition, a database is used and the use of individual functions creates a concurrency problem. Accordingly, I rewrote it like this:
def get_random_foo_or_bar(): "Still prefer foos." try: return get_random_foo() except IndexError: pass try: return get_random_bar() except IndexError: pass raise IndexError, "No foos, no bars"
But I find this to be much less readable, and since I never had any reason to use pass before it feels impractical.
Is there a more efficient pattern, or should I learn to accept pass ?
Note. I would like to avoid any nesting, as other types can be added later.
Edit
Thanks to everyone who said that pass is fine - it is encouraging!
Also thanks to those who suggested replacing the exception with a None return value. I see how this is a useful template, but I would say that it is semantically incorrect in this situation: the functions were asked to perform an impossible task so that they throw an exception. I prefer to monitor the behavior of the random module (for example, random.choice([]) ).
python coding-style exception-handling
Ian mackinnon
source share