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;
As far as the performance is concerned, using try block for code that normally doesn’t raise exceptions is faster than using if statement everytime. So, the decision depends on the probability of excetional cases.
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 timeresult
will actually contain something iterable, I'd use thetry/except
approach. It will be faster if exceptions really are exceptional. Ifresult
isNone
more than 50 % of the time, then usingif
is probably better.To support this with a few measurements:
So, whereas an
if
statement always costs you, it's nearly free to set up atry/except
block. But when anException
actually occurs, the cost is much higher.Moral:
try/except
for flow control,Exception
s are actually exceptional.From the Python docs:
Look Before You Leap is preferable in this case. With the exception approach, a TypeError could occur anywhere in your loop body and it'd get caught and thrown away, which is not what you want and will make debugging tricky.
(I agree with Brandon Corfman though: returning None for ‘no items’ instead of an empty list is broken. It's an unpleasant habit of Java coders that should not be seen in Python. Or Java.)
Your second example is broken - the code will never throw a TypeError exception since you can iterate through both strings and lists. Iterating through an empty string or list is also valid - it will execute the body of the loop zero times.
Your function should not return mixed types (i.e. list or empty string). It should return a list of values or just an empty list. Then you wouldn't need to test for anything, i.e. your code collapses to:
bobince wisely points out that wrapping the second case can also catch TypeErrors in the loop, which is not what you want. If you do really want to use a try though, you can test if it's iterable before the loop
As you can see, it's rather ugly. I don't suggest it, but it should be mentioned for completeness.