嵌套函数的更多 pythonic 方式

More pythonic way to nest functions

这是我的代码:

def reallyquit():
        from easygui import boolbox
        if __debug__: print ("realy quit?")
        answer = boolbox("Are you sure you want to Quit?")
        if answer == 1:
            sys.exit()
        return

columns = ['adr1','adr2','spam','spam', 'spam']

Street = choicebox("Street Address?", title, columns)
    while Street == None:
        reallyquit()
        Street = choicebox("Street Address?", title, columns)

如果用户无意中关闭了一个框,是否有更 pythonic 的方式递归地提出问题?主要寻找最后 4 行的提示,但请随意批评其余部分。

import sys
from easygui import boolbox, choicebox

def reallyquit():
    "Ask if the user wants to quit. If so, exit."
    if __debug__: 
        print("really quit?")
    answer = boolbox("Are you sure you want to Quit?")
    if answer == 1:
        sys.exit()

columns = ['adr1', 'adr2', 'spam', 'spam']
street = None

# ask for address until given or user decides to quit
while street is None:
    street = choicebox("Street Address?", title, columns)
    if street is None:
        reallyquit()

在主逻辑中:如果一个值等于None,通常不会去测试,因为它是一个单例(系统中只有一个,所有出现的None都是为了同样的逻辑 None)。因此 is None 是一个更好的测试。我还使用了更多 Pythonic 代码格式(列表中逗号后的空格、小写变量名)和不重复用户交互调用的测试顺序。

Eric 建议的另一种形式类似于:

while True:
    street = choicebox("Street Address?", title, columns)
    if street is not None:
        break
    reallyquit()

这具有不重复 street is None 测试的优点,但有点长。您对哪个选项看起来更清晰、更合乎逻辑的偏好可能会有所不同。

准备工作:函数中取出imports,在之前缺失的地方导入choicebox。函数给出 定义注释字符串。强制执行每行一个语句标准。并且删除了不必要的 return

这仍然是一个相当粗糙的程序,但现在 "more Pythonic."

不是压倒性的,但 Pythonic 代码外观的标准是 PEP 8. There are tools such as pep8 you can install to check compliance. The deeper or "semantic" part of Pythonic code is sketched out in PEP 20,也称为 "The Zen of Python." 遗憾的是,没有工具可以判断是否符合这些更深层次的原则。需要经验。

我认为这比使用哨兵变量更惯用:

while True:
    street = choicebox("Street Address?", title, columns)
    if street is None:
        reallyquit()
    else:
        break

此外,考虑使用 logging 模块进行调试打印,因此您只需 logging.debug(whatever) 并设置日志记录级别,而不是 if __debug__: print(whatever)