python - 我应该返回一个空的字典而不是 None 吗?

标签 python

我有一个当前返回 Nonedict 的方法。

result,error = o.apply('grammar')

调用者当前必须检查两个键是否存在,以确定返回的对象类型。

if 'imperial' in result:
    # yay
elif 'west' in result:
    # yahoo
else:
    # something wrong?

因为结果可以是None,我正在考虑返回一个空的字典,所以调用者不需要检查它。你怎么看?

作为对比,在re模块中,调用match的结果可以是None

p = re.compile('\w+')
m = p.match( 'whatever' )

但在这种情况下,m 是一个对象实例。就我而言,我正在返回一个应该为空或有一些条目的字典。

最佳答案

是的,我认为返回一个空的字典(或适用的空列表)比返回 None 更可取,因为这避免了对客户端代码的额外检查。

编辑: 添加一些代码示例以进行详细说明:

def result_none(choice):
    mydict = {}
    if choice == 'a':
        mydict['x']  = 100
        mydict['y']  = 1000
        return mydict
    else:
        return None

def result_dict(choice):
    mydict = {}
    if choice == 'a':
        mydict['x']  = 100
        mydict['y']  = 1000
    return mydict

test_dict = result_dict('b')
if test_dict.get('x'):
    print 'Got x'
else:
    print 'No x'

test_none = result_none('b')
if test_none.get('x'):
    print 'Got x'
else:
    print 'No x'

在上面的代码中,检查 test_none.get(x) 抛出一个 AttributeError 作为 result_none 方法可能返回 None。为了避免这种情况,我必须添加一个 额外检查并可能将该行重写为: if test_none is not None and test_none.get('x') 这根本不需要 如果该方法返回一个空字典。如示例所示,检查 test_dict.get('x') 工作正常,因为方法 result_dict 返回一个空字典。

关于python - 我应该返回一个空的字典而不是 None 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5987011/

相关文章:

python - 将十进制值转换为二进制、十六进制和八进制的单个函数不会转换为二进制

python - 使用 numpy 在 Python 中处理 TIFF(导入、导出)

python - 我需要找到文件中某个短语的所有实例,然后打印该短语后下一个单词的排序列表

python - numpy 数组索引 : list index and np. 数组索引给出不同的结果

python - Pandas groupby 在使用 sum() 时抛出错误

python - Reds_r 未被识别为有效的 RGBA 参数

python - 为什么不能迭代?

python - python 中的数学 - 将数据文件转换为矩阵

python - Pip:指定次要版本

python - Pandas 和 GeoPandas 索引和切片