【发布时间】:2016-06-24 16:40:10
【问题描述】:
如果可以避免使用 try except 子句并且它是正常运行的代码的一部分,那么 Python 中是否不鼓励使用 try except 子句?比如下面两个代码sn-ps,哪个是首选?
选项 1:
try:
id = list.index(42)
except:
print("42 not found")
else:
print("ID: ", id)
选项 2:
if 42 in list:
id = list.index(42)
print("ID: ", id)
else:
print("42 not found")
【问题讨论】:
-
不,他们不是。 python中推荐的设计原则是EAFP,而不是LBYL,见Python Glossary
-
仅供参考:
EAFP:请求宽恕比请求许可更容易,LBYL:跳之前先看看 -
嗯,实际上除了简单的检查之外,程序可能还有更多问题。事实上 try/catch 被鼓励并且被认为是好的做法。
-
关于良好 Python 风格的主题 - 不要以标准类型名称命名变量,这可能很诱人。所以没有名为“list”的列表、名为“dict”的字典、名为“tuple”的元组或名为“str”的字符串。
-
@PaulMcGuire 你甚至不应该命名字符串
list、字典str或列表dict:P
标签: python idioms try-except