在python中使用try vs if [英] Using try vs if in python
问题描述
在测试变量是否具有值时,是否有理由决定使用 try
或 if
构造中的哪一个?
例如,有一个函数返回列表或不返回值.我想在处理之前检查结果.以下哪个更可取?为什么?
result = function();如果(结果):对于 r 结果:#处理项目
或
result = function();尝试:对于 r 结果:#处理项目除了类型错误:经过;
相关讨论:
你经常听到 Python 鼓励 EAFP 风格(请求宽恕比许可更容易")超过 LBYL 风格(跳之前先看看").对我来说,这是一个效率和可读性的问题.
在您的示例中(假设函数不是返回列表或空字符串,而是返回列表或 None
),如果您期望 99% 的时间 result
实际上会包含一些可迭代的东西,我会使用 try/except
方法.如果异常确实是异常的,它会更快.如果 result
是 None
超过 50% 的时间,那么使用 if
可能更好.
通过一些测量来支持这一点:
<预><代码>>>>导入时间>>>timeit.timeit(setup="a=1;b=1", stmt="a/b") # 没有错误检查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
块几乎是免费的.但是当Exception
真正发生时,代价要高得多.
道德:
- 使用
try/except
进行流量控制完全没问题(和pythonic"), - 但是当
Exception
实际上是异常时,它最有意义.
来自 Python 文档:
<块引用>EAFP
请求原谅比请求原谅更容易允许.这种常见的 Python 编码样式假定存在有效键或属性和捕获如果假设证明,则例外错误的.这种干净快速的风格是特点是存在许多try
和 except
语句.这技术与 LBYL 形成对比许多其他语言的通用风格如 C.
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/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
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
andexcept
statements. The technique contrasts with the LBYL style common to many other languages such as C.
这篇关于在python中使用try vs if的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!