我有一个当前返回 None
或 dict
的方法。
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/