提高异常与返回无Python功能 [英] Raise exception vs. return None in Python functions

查看:87
本文介绍了提高异常与返回无Python功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python中的用户定义函数中更好的做法是:引发异常或返回None?例如,我有一个函数可以找到文件夹中最新的文件。

  def latestpdf(folder):
#列出文件并对它们进行排序
try:
latest = files [-1]
除了IndexError:
#文件夹为空。
return None#一种可能性
raise FileNotFoundError()#Alternative
else:
return somefunc(最新)#在我的情况下,somefunc解析文件名
解决方案

这是一个语义问题。 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屋!

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