Python中的便宜异常处理? [英] Cheap exception handling in Python?

查看:118
本文介绍了Python中的便宜异常处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了早期的回答,Python中的异常处理便宜,所以我们不应该进行预条件检查。

I read in an earlier answer that exception handling is cheap in Python so we shouldn't do pre-conditional checking.

我以前没有听说过,但我对Python来说比较新。异常处理意味着动态调用和静态返回,而 if 语句是静态调用,静态返回。

I have not heard of this before, but I'm relatively new to Python. Exception handling means a dynamic call and a static return, whereas an if statement is static call, static return.

如何做检查是坏的, try-except 是好的,似乎是另一回事。有人可以向我解释一下吗?

How can doing the checking be bad and the try-except be good, seems to be the other way around. Can someone explain this to me?

推荐答案

你可能会发现这篇文章有帮助: 尝试/除了在Python中的性能:简单的测试 a>其中Patrick Altman进行了一些简单的测试,以了解各种情况下的前期条件检查(在这种情况下是专用于字典键)的性能,仅使用异常。如果你想适应它来测试其他条件,代码也是如此。

You might find this post helpful: Try / Except Performance in Python: A Simple Test where Patrick Altman did some simple testing to see what the performance is in various scenarios pre-conditional checking (specific to dictionary keys in this case) and using only exceptions. Code is provided as well if you want to adapt it to test other conditionals.

他得出的结论是:

从这些结果中,我认为很快确定一些
结论是公平的:

From these results, I think it is fair to quickly determine a number of conclusions:


  1. 如果元素不存在的可能性很高,那么
    你最好使用has_key检查

  2. 如果你不执行任何异常,如果它是
    提高,那么你最好不要
    放一个除了

  3. 如果可能的话该元素确实存在,那么使用try / except
    块而不是使用has_key,
    的优点非常轻微,所以有一个非常
    的优势。优点是非常轻微。


这篇关于Python中的便宜异常处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆