python - 使用异常来控制代码流

标签 python exception

afaik 使用异常来处理代码流是错误的。我正在使用一个代码,该代码有一个名为 getEntity(id) 的方法,当找不到实体时,getEntity 会抛出 DoesNotExist 异常。没有 entityExists(id) 方法。要检查实体是否存在,代码通常会执行以下操作:

try: 
   getEntity(id)
catch DoesNotExist as e:
   # entity does not exist

在我看来这样会更好:

if not entityExists(id):
   # entity does not exist

这个^是常识?我认为代码是这样的,因为它使用 Django 并且它正在复制 Django 异常名称 (DoesNotExist) 及其处理实体不存在的通常方式。

这个问题并不特定于 Python,但我用作示例的代码是用 Python 编写的,因此我用 Python 标记了这个问题。

最佳答案

这被称为 EAFP或者请求宽恕比请求许可更容易。来自 The Python Glossary :

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 LBYL style common to many other languages such as .

LBYL意思是三思而后行。再次来自 The Python Glossary :

This coding style explicitly tests for pre-conditions before making calls or lookups. This style contrasts with the EAFP approach and is characterized by the presence of many if statements.

然后它继续为您的 if not entityExists(id): 建议提供一个很好的反例:

In a multi-threaded environment, the LBYL approach can risk introducing a race condition between “the looking” and “the leaping”. For example, the code, if key in mapping: return mapping[key] can fail if another thread removes key from mapping after the test, but before the lookup. This issue can be solved with locks or by using the EAFP approach.

在用 Python(或任何语言)编写时,遵循该语言的惯用语会有所帮助,这会使您的代码更容易被阅读它的其他人理解。

关于python - 使用异常来控制代码流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16451257/

相关文章:

python - 是否可以在 listctrl 中将数字设置为字符串

python脚本在matplotlib inline和QT后端之间切换

database - 如何删除具有外键依赖项的重复行?

java - 如何正确关闭资源?

python - 多列上的 PySpark 数据框过滤器

python - 无法执行 collectstatic

java - 什么时候在代码中捕获 RuntimeExceptions?

r - R 中的异常处理和堆栈展开

javascript - 为什么 d3.json 返回 "null"?

java - 如何调试在写入字符串时导致转换错误的 xml 对象?