Using try vs if in python

后端 未结 9 1028
终归单人心
终归单人心 2020-11-22 12:59

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 f

相关标签:
9条回答
  • 2020-11-22 13:15

    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
    
    0 讨论(0)
  • 2020-11-22 13:23

    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.

    0 讨论(0)
  • 2020-11-22 13:24

    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.

    0 讨论(0)
  • 2020-11-22 13:26

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 13:29

    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
    
    0 讨论(0)
提交回复
热议问题