嵌套 if - 还有什么 Pythonic ?

use*_*030 1 python if-statement nested indentation pep

这两个函数做同样的事情。

def function1(self):
    a = self.get_a()
    b = self.get_b()
    c = self.get_c()
    r = None

    if a:
        r = a
        if b:
            r = b
            if c:
                r = c
            else:
                print("c not set.")
        else:
            print("b not set.")
    else:
        print("a not set.")

    return r



def function2(self):
    a = self.get_a()
    b = self.get_b()
    c = self.get_c()
    r = None

    if not a:
        print("a not set.")
        return r

    r = a
    if not b:
        print("b not set.")
        return r

    r = b
    if not c:
        print("c not set.")

    r = c
    return r
Run Code Online (Sandbox Code Playgroud)

function1() 会创建很长的行,如果嵌套越多,这与 PEP8 的行长度限制 78 冲突。

function2() 可能更难阅读/理解并且有更多的返回语句。行长在这里没问题。

哪个更pythonic?

Wil*_*ill 7

Pythonic 代码的原则之一是“扁平优于嵌套”。在此基础上,我会说function2()客观上更Pythonic。这可以在PEP-20: The Zen of Python 中看到:

Python 之禅

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Run Code Online (Sandbox Code Playgroud)

这可以通过import this在 Python 解释器中键入来查看。

  • 感谢“导入这个”。我实际上从未见过这个 (4认同)