寻找更多pythonic的东西

时间:2011-11-01 00:19:02

标签: django refactoring python

这看起来真的很难看,有没有办法让它看起来更像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

4 个答案:

答案 0 :(得分: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))

答案 1 :(得分:1)

您的所有问题都来自None。清理它们,你的逻辑变得微不足道。

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)

答案 2 :(得分: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

答案 3 :(得分:0)

内部if / elif / else链可以用and-operator和or-operator替换。只要您看到return Truereturn False代替每个替代方案的正文,这种替换就应该是自动的。

此外,还有多个对self.cleaned_data的引用可以用以下方法解决:

cleaned = self.cleaned_data