Using 'try' vs. 'if' in Python
Asked Answered
C

9

216

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;

Related discussion:

Checking for member existence in Python

Concede answered 2/12, 2009 at 20:58 Comment(1)
Bear in mind that if your #process items stanza is liable to throw a TypeError you need to wrap in another try: except: block. For this specific example I'd by just using an if:Conclusion
I
356

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 time result will actually contain something iterable, I'd use the try/except approach. It will be faster if exceptions really are exceptional. If result is None more than 50 % of the time, then using if is probably better.

To support this with a few measurements:

>>> import timeit
>>> timeit.timeit(setup="a=1;b=1", stmt="a/b") # no error checking
0.06379691968322732
>>> timeit.timeit(setup="a=1;b=1", stmt="try:\n a/b\nexcept ZeroDivisionError:\n pass")
0.0829463709378615
>>> timeit.timeit(setup="a=1;b=0", stmt="try:\n a/b\nexcept ZeroDivisionError:\n pass")
0.5070195056614466
>>> timeit.timeit(setup="a=1;b=1", stmt="if b!=0:\n a/b")
0.11940114974277094
>>> timeit.timeit(setup="a=1;b=0", stmt="if b!=0:\n a/b")
0.051202772912802175

So, whereas an if statement always costs you, it's nearly free to set up a try/except block. But when an Exception actually occurs, the cost is much higher.

Moral:

  • It's perfectly OK (and "pythonic") to use try/except for flow control,
  • but it makes sense most when Exceptions are actually exceptional.

From the Python docs:

EAFP

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

Indemnification answered 2/12, 2009 at 21:10 Comment(11)
Thank you. I see that in this case the rationale can be the expectation of the result.Concede
.... and that's one (of many) reasons why it's so hard to do a real optimizing JIT for Python. As the recently in beta LuaJIT 2 proves, dynamic languages can be really, really fast; but it heavily depends on the initial language design and the style it encourages. (on a related note, language design is why even the very best JavaScirpt JITs can't compare to LuaJIT 1, much less 2)Digitalin
@Digitalin do you know something I could read about what the design differences are that affect the potential benefit of JITs?Solidify
Time traveler here. I did similar tests with dictionaries and KeyErrors and I found that in several (trivial) examples using if key in dict: was faster than the try/except block... in both cases. So I would test the performance of your own code before assuming one is better than the other. Or, just choose which one is more readable.Sturmabteilung
@2rs2ts: I just did similar timings myself. In Python 3, try/except was 25 % faster than if key in d: for cases where the key was in the dictionary. It was much slower when the key wasn't in the dictionary, as expected, and consistent with this answer.Indemnification
@TimPietzcker It's probably the difference between 2.7 and 3.x, then.Sturmabteilung
I know this is an old answer, however: using statements like 1/1 with timeit is not a great choice, because they will be optimized out (see dis.dis('1/1') and note that no division occurs).Tarkany
@AndreaCorbellini: Thanks for noticing this - I've replaced the tests with slightly more meaningful ones. Fortunately, the general message still holds true :)Indemnification
Thank you for your answer. From your results, an exception that happens up to ~20% of the time, or in no critical code seems to be ok. (btw, in my machine, (Python 2.7.11 |Anaconda 2.4.1 (64-bit)| (default, Feb 16 2016, 09:58:36) [MSC v.1500 64 bit (AMD64)), the numbers are a bit worse, the raised exception is ~13 times slower, so that would signify ~7% of the time as the limit)Huntlee
It also depends on the operation you're willing to carry out. A single division is fast, catching an error is somewhat expensive. But even in cases where the cost of exception handling is acceptable, carefully think about what you're asking the computer to do. If the operation itself is very expensive regardless of its results, and there's a cheap way to tell if success is possible: Use it. Example: Don't copy half of a file just to realize there's not enough space.Fungiform
Late '15 MBA: none: 0.11s (warm run: 0.06s), try: 0.06s, try error: 0.46s, if: 0.09s, if error: 0.04s.Moujik
L
19

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:

for r in function():
    # process items
Lowpressure answered 2/12, 2009 at 21:11 Comment(4)
I completely agree with you on that point; however, the function is not mine, and I am just using it.Concede
@artdanil: So you could wrap that function in one that you write that works like the one that Brandon Corfman is thinking of.Antemeridian
which begs the question: should the wrapper use an if or a try to handle the non-iterable case?Bebeeru
@Antemeridian which is exactly what I am trying to do. So as @jcd pointed out, The question is about how I should handle situation in the wrapper function.Concede
F
13

Please ignore my solution if the code I provide is not obvious at first glance and you have to read the explanation after the code sample.

Can I assume that the "no value returned" means the return value is None? If yes, or if the "no value" is False boolean-wise, you can do the following, since your code essentially treats "no value" as "do not iterate":

for r in function() or ():
    # process items

If function() returns something that's not True, you iterate over the empty tuple, i.e. you don't run any iterations. This is essentially LBYL.

Featured answered 2/12, 2009 at 21:57 Comment(0)
T
7

Generally, the impression I've gotten is that exceptions should be reserved for exceptional circumstances. If the result is expected never to be empty (but might be, if, for instance, a disk crashed, etc), the second approach makes sense. If, on the other hand, an empty result is perfectly reasonable under normal conditions, testing for it with an if statement makes more sense.

I had in mind the (more common) scenario:

# keep access counts for different files
file_counts={}
...
# got a filename somehow
if filename not in file_counts:
    file_counts[filename]=0
file_counts[filename]+=1

instead of the equivalent:

...
try:
    file_counts[filename]+=1
except KeyError:
    file_counts[filename]=1
Tyrothricin answered 2/12, 2009 at 21:9 Comment(2)
This is an example of the difference between the approaches Tim Pietzcker mentions: The first is LBYL, the second is EAFPTyrothricin
Just a quick note that ++ doesn't work in python, use += 1 instead.Agbogla
T
5

Which of the following would be more preferable and why?

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.)

Tocsin answered 2/12, 2009 at 22:39 Comment(0)
T
4

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.

Tourbillion answered 2/12, 2009 at 21:7 Comment(1)
In their example, the function is said to either return a list or doesn't return a value. In which case result == None, and a TypeError is thrown.Tarazi
R
3

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

result = function();
try:
    it = iter(result)
except TypeError:
    pass
else:
    for r in it:
        #process items

As you can see, it's rather ugly. I don't suggest it, but it should be mentioned for completeness.

Rattler answered 3/12, 2009 at 18:21 Comment(1)
In my eyes, running into type errors intentionaly is always bad coding style. A developer should know what to expect and be prepared to handle that values without exceptions. Whenever an operation did what it was supposed to do (from the programmer's point of view) and the expected results are a list or None, always check the result with is None or is not None. On the other side it is also bad style to raise Exceptions for legitimate results. Exceptions are for the unexpected things. Example: str.find() returns -1 if nothing is found, because the search itself completed without errors.Fungiform
A
1

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.

Ashti answered 3/12, 2009 at 2:33 Comment(0)
N
-7

As a general rule of thumb, you should never use try/catch or any exception handling stuff to control flow. Even though behind the scenes iteration is controlled via the raising of StopIteration exceptions, you still should prefer your first code snippet to the second.

Nerva answered 2/12, 2009 at 21:12 Comment(2)
This is true in Java. Python embraces EAFP quite heavily.Gypsophila
It's still an odd practice. The brains of most programmers are wired to skip over EAFP in my experience. They end up wondering why a certain path was selected. This being said, there is a time and place to break every rule.Nerva

© 2022 - 2024 — McMap. All rights reserved.