擅长:python、mysql、java
<p>我觉得有点奇怪,<code>get_random_foo()</code>在不将索引作为参数时引发索引器错误(但在上下文中可能更合理)。为什么不让<code>get_random_foo()</code>或包装器捕获错误并返回None呢?</p>
<pre><code>def get_random_foo_wrapper():
try:
return get_random_foo()
except IndexError:
return None
def get_random_foo_or_bar():
"I'd rather have a foo than a bar."
return get_random_foo_wrapper() or get_random_bar_wrapper() or None
</code></pre>
<p><strong>编辑</strong>:我应该提到,如果foo&bar是可能求值为False的对象(比如说0或“”),那么<code>or</code>比较将跳过那些不好的对象</p>