Using try vs if in python

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


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/bnexcept ZeroDivisionError:n pass")
0.0829463709378615
>>> timeit.timeit(setup="a=1;b=0", stmt="try:n a/bnexcept 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 Exception s 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.


    Your function should not return mixed types (ie 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, ie your code collapses to:

    for r in function():
        # process items
    

    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, ie you don't run any iterations. This is essentially LBYL.

    链接地址: http://www.djcxy.com/p/4918.html

    上一篇: 在Python中检查成员存在

    下一篇: 使用尝试与如果在Python中