2011-11-01 123 views
2

這看起來真的很醜,它有辦法讓它看起來更pythonic?尋找更多pythonic

if self.cleaned_data['string1_val'] == '' and latestSI.string1_val is None : 
    if self.cleaned_data['string2_val'] == '' and latestSI.string2_val is None : 
     return False 
    elif self.cleaned_data['string2_val'] == latestSI.string2_val : 
     return False 
    else: 
     return True 
elif self.cleaned_data['string1_val'] == latestSI.string1_val : 
    if self.cleaned_data['string2_val'] == '' and latestSI.string2_val is None : 
     return False 
    elif self.cleaned_data['string2_val'] == latestSI.string2_val : 
     return False 
    else: 
     return True 
else: 
    return True 
+0

pythonic?嗯,這甚至​​意味着什麼? – NickLH

+0

@NickLH:Python程序員使用它來表示「乾淨」或「慣用」,這聽起來很酷。 –

+2

+1我認爲這是一個很好的問題。編程人員的警鐘響了起來,他試圖利用語言功能以更清晰的方式進行編碼。 –

回答

1

你所有的問題都來自None s。清理它們,你的邏輯變得微不足道。

cd1 = self.cleaned_data['string1_val'] 
lsi1 = latestSI.string1_val 
cd2 = self.cleaned_data['string2_val'] 
lsi2 = latestSI.string2_val 
if lsi1 is None: 
    lsi1 = '' 
if lsi2 is None: 
    lsi2 = '' 
return not (cd1 == lsi1 and cd2 == lsi2) 
+0

我不喜歡這個解決方案是它專門用於這個精確的代碼片段。使用變量賦值,和/或操作符以及分解公共子表達式的解決方案是完全一般的。而且,我仍然發現上面的「清理」代碼比其他解決方案更難以進行精神分析。 –

+0

我明白你的意思了。如果它們是「無」,則將值設置爲「'」,然後您可以制定更清晰的邏輯。太好了! – Sevenearths

2
def eq(x,y): 
    return x == ('' if y is None else y) 

if eq(self.cleaned_data['string1_val'],latestSI.string1_val): 
    return not eq(self.cleaned_data['string2_val'],latestSI.string2_val) 

嗯。看起來問題已經改變。由於增加了最終else: True的,邏輯可以被改變到

return not (eq(self.cleaned_data['string1_val'],latestSI.string1_val) 
      and eq(self.cleaned_data['string2_val'],latestSI.string2_val)) 
0

內如果/ elif的/其他鏈能夠與和運營商和或運營商來代替。每當您看到每個備選方案的主體爲return Truereturn False時,此替換應該幾乎是自動的。

此外,還有一些可以分解出一起self.cleaned_data多個引用:

cleaned = self.cleaned_data 
1

認爲這個表達式等價(我不能測試它,因爲我不有權訪問您的其他代碼)。但是,這真的很長,很難理解,如果我是你,我寧願保持它不變:

if (self.cleaned_data['string1_val'] == latestSI.string1_val) or (not self.cleaned_data['string1_val'] and not latestSI.string1_val): 
    return (not self.cleaned_data['string2_val'] or not latestSI.string2_val) and self.cleaned_data['string2_val'] != latestSI.string2_val 
else: 
    return True 
+0

離開「返回True」意味着還有一個級別。注意通過使用額外的布爾運算符來改進您的答案,並可能在有意義的變量中保存中間分組?另外,考慮刪除self.cleaned_data公共子表達式。 (另外,如果你無法判斷它是否正確,答案並不是很好的建議。) –