Say there's a kind of function that returns either some value or None
, and we have three such functions: egg
, ham
and spam
.
The goal is to call egg
, ham
, spam
and return the first non-None value returned, and if there's no valid value return, return None
.
The most straightforward way would be:
def func():
ret = egg()
if ret:
return ret
ret = ham()
if ret:
return ret
ret = spam()
if ret:
return ret
return None
or, a smarter but maybe harder to read solution is:
def func():
return egg() or ham() or spam()
Here're my questions (there could be more than three candidate functions to call):
- Is the second way hard to read and should be avoided?
- Is there a better way to design such control flow? I remember there's something in Lisp that does exactly this, but what about in Python?