我应该返回一个空字典而不是 None



我有一个当前返回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)抛出一个属性错误result_none方法都可能返回 None。为了避免这种情况,我必须添加一个其他检查,可能会将该行重写为: 根本不需要if test_none is not None and test_none.get('x')如果该方法返回空字典。如示例所示,检查test_dict.get('x')工作正常,因为该方法result_dict返回空字典。

我不完全确定这段代码的上下文,但我会说返回 None 表明存在某种错误并且无法完成操作。返回空字典表示成功,但没有任何内容与添加到字典的条件匹配。

我来自一个完全不同的背景(C++游戏开发),所以把它当作它的价值:

不过,出于性能原因,返回 None 并保存创建空字典可能涉及的任何开销(尽管最小)可能会很好。我发现,一般来说,如果你使用脚本语言,你并不关心该代码的性能。如果你是,除非出于某种不可避免的原因需要,否则你可能不会用上述语言编写该功能。

正如其他人所说,空洞的字典是虚假的,所以没有问题。但是,返回空洞的字典的想法在我的嘴里留下了不好的味道。我不禁觉得返回空字典可能会隐藏返回None会揭示的错误。不过,这只是一种直觉。

经过更多思考,我认为返回一个空dict可能更 Pythonic。一个好的经验法则可能是,如果你编写一个返回容器的函数/方法,则始终返回一个空容器。此行为的几个示例:

"".split() == []
filter(lambda a:False, [1,2]) == []
range(1, -1) == []
re.findall('x', '') = []

相反,如果您试图获取单个对象,您别无选择,只能返回None我想。所以我想None就像单个物体的空容器!感谢KennyTM向我提出一些意义:D

Python supports returning multiple values. Hence, you can return a status of success along with an empty dictionary. The caller first verifies the return code and then uses the dictionary.
def result_none(choice):
    mydict = {}
    retcode = -1
    if choice == 'a':
        mydict['x']  = 100
        mydict['y']  = 1000
        retcode = 0
    return mydict, retcode
retcode, mydict = result_none('a')
if retcode == 0:
   <<use dictionary>>

最新更新