你经常听到Python鼓励EAY风格(“更容易要求宽恕比许可”)在LBYL风格(“看你飞跃”之前)。对我来说,这是一个效率和可读性的问题。
在你的例子中(说,而不是返回一个列表或一个空字符串,函数是返回一个列表或None),如果你希望99%的时间结果将实际上包含一些可迭代的,我会使用try /除了方法。如果异常真的是例外,它会更快。如果结果没有超过50%的时间,那么使用if可能更好。
为了支持这一点与几个测量:
>>> 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
所以,虽然if语句总是花费你,几乎可以免费设置一个try / except块。但是当一个异常实际发生时,成本要高得多。
道德:
>这是完全OK(和“pythonic”)使用try / except流控制,
>但是,当异常实际上是例外时,它是最有意义的。
从Python文档:
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 07000 style common to many other languages such as C.