提高异常与返回无Python功能 [英] Raise exception vs. return None in Python functions
问题描述
def latestpdf(folder):
#列出文件并对它们进行排序
try:
latest = files [-1]
除了IndexError:
#文件夹为空。
return None#一种可能性
raise FileNotFoundError()#Alternative
else:
return somefunc(最新)#在我的情况下,somefunc解析文件名
$另一个选项是留下异常,并在调用者代码中处理它,但是我认为处理一个FileNotFoundError比IndexError更为清晰。 。还是用不同的名称来重新提出异常是不好的形式?解决方案这是一个语义问题。 foo = latestpdf(d)
意味着?
没有最新的文件?那么确定,只要返回None。
您是否期望总是找到最新的文件?提出例外。是的,重新提出一个更合适的例外是很好的。
如果这只是一个应用于任何目录的通用函数,我会做前者和返回无。如果目录是例如意图是包含应用程序已知文件集的特定数据目录,我会引发一个例外。
What's better practice in a user-defined function in Python: raise an exception or return None? For example, I have a function that finds the most recent file in a folder.
def latestpdf(folder):
# list the files and sort them
try:
latest = files[-1]
except IndexError:
# Folder is empty.
return None # One possibility
raise FileNotFoundError() # Alternative
else:
return somefunc(latest) # In my case, somefunc parses the filename
Another option is leave the exception and handle it in the caller code, but I figure it's more clear to deal with a FileNotFoundError than an IndexError. Or is it bad form to re-raise an exception with a different name?
解决方案 It's really a matter of semantics. What does foo = latestpdf(d)
mean?
Is it perfectly reasonable that there's no latest file? Then sure, just return None.
Are you expecting to always find a latest file? Raise an exception. And yes, re-raising a more appropriate exception is fine.
If this is just a general function that's supposed to apply to any directory, I'd do the former and return None. If the directory is, e.g., meant to be a specific data directory that contains an application's known set of files, I'd raise an exception.
这篇关于提高异常与返回无Python功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!