Python编码实践: Return None vs Return same datatype with empty value?

标签 python

<分区>

是否应使用相同的数据类型从函数返回或分配默认值?或无?什么是更好的编码实践,为什么?

例如。 python中的一些伪代码:

/1

def my_position():   # returns a positive integer if found
    if(object is present):
          position = get_position()
          return position # eg 2,3,4,6
    else: 
          return None     # or return -1 or 0 ??

/2

def get_database_rows():    
    do query to whatever database
    if(rows are found):
       return [list of rows]
    else:
       return None  # or return empty list []  ?

/3

the_dictionary = {'a' : 'john','b':'mike','c': 'robert' }  # values are names i.e. non empty string
my_new_var = the_dictionary.get('z', None)  # or the_dictionary.get('z','')  ?

最佳答案

  1. 如果找不到该项目,则引发 IndexError。这就是 Python 的 list 所做的。 (或者可能在进行二分查找或类似操作时返回项目应该存在的索引。)

  2. 从逻辑上考虑您的函数的作用:如果它返回 DB 中满足某些条件的所有项目的列表,并且没有这样的项目,那么返回一个空列表是有意义的,因为这允许所有常用列表操作(lenin)无需显式检查即可运行。

    但是,如果缺少必需项表示不一致,则引发异常。

  3. 我之前的评论尤其适用于这种情况:这取决于您将如何处理您获得的值(value)。当找不到键时,普通的 dict 只会引发 KeyError 。您正在用一个值替换该异常,因此您应该知道哪个值在您的程序上下文中有意义。如果没有值,那么就让异常飞吧。

也就是说,返回 None 通常不是一个好主意,因为它可能掩盖错误。 None 是 Python 中的默认返回值,因此返回它的函数可能仅表示其作者忘记了 return 语句:

def food(what):
    if what == HAM:
        return "HAM!"
    if what == SPAM:
        return " ".join(["SPAM" for i in range(10)])
    # should raise an exception here

lunch = food(EGGS)    # now lunch is None, but what does that mean?

关于Python编码实践: Return None vs Return same datatype with empty value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14583638/

相关文章:

python - 加速numpy中的数组分析

python - 按字符大小分割,但在 Python 正则表达式中完全包含单词

python - 创建单个 python 可执行模块

python - 在图像上重复创建文本的算法

python - 如何选择 Pandas 中的行范围?

python - 将 Python 类转换为 Numpy 数组

python - Numpy.empty() 创建具有非空值的数组

python - 如何为当前列表组添加 `active` 类?

python - 使用python和mock模拟ReviewBoard第三方库

python - `numpy.einsum` 是如何工作的?