cha*_*ver 14 python error-handling assert
我有一个关于Python中的错误检查的问题.假设我有一个将文件路径作为输入的函数:
def myFunction(filepath):
infile = open(filepath)
#etc etc...
Run Code Online (Sandbox Code Playgroud)
一个可能的先决条件是文件应该存在.
有几种可能的方法来检查这个前提条件,我只是想知道最好的方法是什么.
i)检查if语句:
if not os.path.exists(filepath):
raise IOException('File does not exist: %s' % filepath)
Run Code Online (Sandbox Code Playgroud)
这是我通常会这样做的方式,尽管如果文件不存在,Python会引发相同的IOException,即使我没有提出它.
ii)使用assert检查前提条件:
assert os.path.exists(filepath), 'File does not exist: %s' % filepath
Run Code Online (Sandbox Code Playgroud)
使用asserts似乎是检查前/后条件的"标准"方式,所以我很想使用它们.但是,在执行期间使用-o标志时,可能会关闭这些断言,这意味着可能会关闭此检查,这似乎有风险.
iii)根本不处理前提条件
这是因为如果filepath不存在,则无论如何都会生成异常,并且异常消息足够详细,以便用户知道该文件不存在
我只是想知道上面哪一项是我应该用于我的代码的标准做法.
unu*_*tbu 15
如果您要做的只是引发异常,请使用选项iii:
def myFunction(filepath):
with open(filepath) as infile:
pass
Run Code Online (Sandbox Code Playgroud)
要以特殊方式处理异常,请使用try...except块:
def myFunction(filepath):
try:
with open(filepath) as infile:
pass
except IOError:
# special handling code here
Run Code Online (Sandbox Code Playgroud)
在任何情况下都不首先检查文件是否存在(选项i或ii),因为在检查或断言发生之间以及python尝试打开文件之间的时间内,文件可能被删除或更改(例如使用符号链接),这可能导致错误或安全漏洞.
此外,从Python 2.6开始,打开文件时的最佳做法是使用with open(...)语法.这可以保证文件将被关闭,即使with-block 内发生异常也是如此.
在Python 2.5中,with如果您在脚本前加上,则可以使用语法
from __future__ import with_statement
Run Code Online (Sandbox Code Playgroud)
我认为你应该混合使用 iii) 和 i)。如果你确实知道 python 会抛出异常(即情况 iii),那么就让 python 来做吧。如果还有一些其他先决条件(例如,您的业务逻辑要求),您应该抛出自己的异常,甚至可能从Exception.
恕我直言,使用断言太脆弱了,因为它们可能会被关闭。