Is there a rationale to decide which one of try or if constructs to use, when testing variable to have a value?
For example, there is a function that returns either a list or doesn’t return a value. I want to check result before processing it. Which of the following would be more preferable and why?
result = function();
if (result):
for r in result:
#process items
or
result = function();
try:
for r in result:
# Process items
except TypeError:
pass;
You often hear that Python encourages EAFP style (“it’s easier to ask for forgiveness than permission”) over LBYL style (“look before you leap”). To me, it’s a matter of efficiency and readability.
In your example (say that instead of returning a list or an empty string, the function were to return a list or
None), if you expect that 99 % of the timeresultwill actually contain something iterable, I’d use thetry/exceptapproach. It will be faster if exceptions really are exceptional. IfresultisNonemore than 50 % of the time, then usingifis probably better.To support this with a few measurements:
So, whereas an
ifstatement always costs you, it’s nearly free to set up atry/exceptblock. But when anExceptionactually occurs, the cost is much higher.Moral:
try/exceptfor flow control,Exceptions are actually exceptional.From the Python docs: