if-not 一行以避免重复块,python 风格的问题

if-not one-liners to avoid repetitive blocks, a matter of python style

我正在从事一个个人 API 项目,该项目涉及接受带有关键字的请求,其中许多是必需的。正因为如此,我发现自己写了很多看起来像这样的代码:

def post(self, urlSafeKey=None):
    if urlSafeKey:
       # do a bunch 
       # of stuff
       # here
    else:
       self.abort(400, detail="A key parameter is required")

我被告知更喜欢 if - else 而不是使用 if not 测试底片以获得可读性但是当我检查并将所有这些块更改为这样的东西时......

def post(self, urlSafeKey=None):
    if not urlSafeKey: self.abort(400, detail="A key parameter is required")
    # do a bunch 
    # of stuff
    # here

…它看起来更干净、更短,但我担心这是一种令人讨厌的文体习惯,最终可能不太清晰。

Python 世界对此有共识吗?

一般来说,遵循的最佳做法是 best practice。我不推荐单行语句。但我认为测试 not urlSafeKey.

没有任何问题
def post(self, urlSafeKey=None):
    if not urlSafeKey:
       self.abort(400, detail="A key parameter is required")
    # do a bunch 
    # of stuff
    # here

假设 self.abort 引发异常(并因此终止函数 post),我相信最好避免将正常情况的代码嵌套在 if 中。 import this 在交互式解释器提示中被提醒 "Zen of Python",其中一个公案是 "flat is better than nested":-)。

单行

if not urlSafeKey: self.abort(400, detail="A key parameter is required")

就我个人的口味而言有点长 -- 我更喜欢基于 if 的一行,以限制在非常简短的情况下,例如 if cond: returnif cond: continueif cond: break,否则使用两行。但与更喜欢避免嵌套(即检查 "I'm done" 条件并在你知道它完成时尽早退出函数或循环)相比,这确实是一个小问题(纯粹是词汇!),一个Python-禅级问题!-)