簡體   English   中英

我應該返回一個空字典而不是 None 嗎?

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

我有一個當前返回Nonedict的方法。

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

調用者當前必須檢查是否存在兩個鍵來決定返回哪種 object。

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

因為 result 可以是None ,我正在考慮返回一個空的 dict ,所以調用者不需要檢查它。 你怎么看?

為了比較,在re模塊中,調用match的結果可能會導致None

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

但在這種情況下, m是一個 object 實例。 就我而言,我正在返回一個應該為空或有一些條目的字典。

是的我認為返回一個空的dict(或適用的空列表)比返回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')如果方法返回空dict則根本不需要。 如示例所示,檢查test_dict.get('x')正常,因為方法result_dict返回一個空的dict。

我不完全確定這段代碼的上下文,但我會說返回None表示有某種錯誤,操作無法完成。 返回一個空字典表示成功,但沒有任何內容符合添加到字典的標准。

我來自一個完全不同的背景(C ++游戲開發),所以請考慮它的價值:

但是出於性能原因,可能很高興返回None並保存任何開銷,盡管很小,但可能涉及創建空字典。 我發現,通常情況下,如果您使用的是腳本語言,那么您並不關心該代碼的性能。 如果您是,您可能不會用所述語言編寫該功能,除非出於某些不可避免的原因需要。

經過深思熟慮,我認為返回一個空的dict可能更像Pythonic。 如果你編寫一個返回容器的函數/方法,一個好的經驗法則可能是總是返回一個空容器 這種行為的幾個例子:

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

相反,如果你想要獲得一個對象,你別無選擇,只能返回我想的None 所以我猜None像單個對象的空容器! 感謝KennyTM對我有所了解:D

正如其他人所說,一個空的字典是假的,所以那里沒有問題。 但回歸空謎的想法在我的嘴里留下了不好的味道。 我不禁覺得返回一個空的dict可能會隱藏返回None會顯示的錯誤。 不過,這只是一種直覺。

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