Using try vs if in python

后端 未结 9 1037
终归单人心
终归单人心 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:39

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

提交回复
热议问题