简体   繁体   English

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

[英]Should I return an empty dict instead of None?

I have a method that currently returns None or a dict .我有一个当前返回Nonedict的方法。

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

The caller currently has to check for the existence of two keys to decide what kind of object was returned.调用者当前必须检查是否存在两个键来决定返回哪种 object。

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

Because result can be None , I'm thinking of returning an empty dict instead, so the caller does not need to check for that.因为 result 可以是None ,我正在考虑返回一个空的 dict ,所以调用者不需要检查它。 What do you think?你怎么看?

For comparison, in the re module, the result of calling match can result in None .为了比较,在re模块中,调用match的结果可能会导致None

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

But in this case, m is an object instance.但在这种情况下, m是一个 object 实例。 In my case, I am returning a dict which should either be empty or have some entries.就我而言,我正在返回一个应该为空或有一些条目的字典。

Yes I think returning an empty dict (or where applicable an empty list) is preferable to returning None as this avoids an additional check in the client code. 是的我认为返回一个空的dict(或适用的空列表)比返回None更可取,因为这样可以避免在客户端代码中进行额外的检查。

EDIT: Adding some code sample to elaborate: 编辑:添加一些代码示例来详细说明:

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'

In the above code the check test_none.get(x) throws an AttributeError as result_none method can possibly return a None. 在上面的代码中,检查test_none.get(x)抛出一个AttributeError,因为result_none方法可能返回None。 To avoid that I have to add an additional check and might rewrite that line as: if test_none is not None and test_none.get('x') which is not at all needed if the method were returning an empty dict. 为了避免这种情况,我必须添加一个额外的检查,并可能将该行重写为: if test_none is not None and test_none.get('x')如果方法返回空dict则根本不需要。 As the example shows the check test_dict.get('x') works fine as the method result_dict returns an empty dict. 如示例所示,检查test_dict.get('x')正常,因为方法result_dict返回一个空的dict。

I'm not entirely sure of the context of this code, but I'd say returning None suggests that there was somehow an error and the operation could not be completed. 我不完全确定这段代码的上下文,但我会说返回None表示有某种错误,操作无法完成。 Returning an empty dictionary suggests success, but nothing matched the criteria for being added to the dictionary. 返回一个空字典表示成功,但没有任何内容符合添加到字典的标准。

I come from a completely different background (C++ Game Development) so take this for what it's worth: 我来自一个完全不同的背景(C ++游戏开发),所以请考虑它的价值:

For performance reasons though, might be nice to return None and save whatever overhead, though minimal, may be involved in creating an empty dictionary. 但是出于性能原因,可能很高兴返回None并保存任何开销,尽管很小,但可能涉及创建空字典。 I find that, generally, if you're using a scripting language, you're not concerned about the performance of that code. 我发现,通常情况下,如果您使用的是脚本语言,那么您并不关心该代码的性能。 If you were, you probably wouldn't be writing that feature in said language unless required for some unavoidable reason. 如果您是,您可能不会用所述语言编写该功能,除非出于某些不可避免的原因需要。

After more thought, I think returning an empty dict might be more Pythonic. 经过深思熟虑,我认为返回一个空的dict可能更像Pythonic。 A good rule of thumb might be to always return an empty container if you write a function/method which returns a container . 如果你编写一个返回容器的函数/方法,一个好的经验法则可能是总是返回一个空容器 Several examples of this behavior: 这种行为的几个例子:

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

In contrast if you are trying to get a single object, you have no choice but to return None I suppose. 相反,如果你想要获得一个对象,你别无选择,只能返回我想的None So I guess None is like the empty container for single objects! 所以我猜None像单个对象的空容器! Thanks to KennyTM for arguing some sense into me :D 感谢KennyTM对我有所了解:D

As others have said, an empty dict is falsy, so there's no problem there. 正如其他人所说,一个空的字典是假的,所以那里没有问题。 But the idea of returning an empty dict leaves a bad taste in my mouth. 但回归空谜的想法在我的嘴里留下了不好的味道。 I can't help but feel that returning an empty dict could hide errors that returning None would reveal. 我不禁觉得返回一个空的dict可能会隐藏返回None会显示的错误。 Still, it's just a gut feeling. 不过,这只是一种直觉。

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>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM