Skip to main content
 首页 » 编程设计

带有 if 长谓词的 Python 风格

2024年11月01日11lhb25

<分区>

考虑这段代码:

if (something1 is not None and 
    check_property(something_else) and 
    dr_jekyll is mr_hyde): 
    do_something(*args) 
    other_statements() 

尽管代码是以 PEP-8 方式编写的,但显然很难分辨谓词在哪里结束以及主体语句从哪里开始。

我们设计了两种变体:

if ((something1 is not None) and 
    (check_property(something_else)) and 
    (dr_jekyll is mr_hyde)): 
    do_something(*args) 
    other_statements() 

这是丑陋的

if (something1 is not None and 
        check_property(something_else) and 
        dr_jekyll is mr_hyde): 
    do_something(*args) 
    other_statements() 

这也很丑。

我个人更喜欢#1,而我的同事使用#2。是否有一个不丑陋且符合 PEP-8 标准的解决方案,可以提高上述方法的可读性?