带长谓词的Python样式

2024-04-28 15:20:57 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑以下代码:

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兼容的规范解决方案,可以提高上述方法的可读性?你知道吗


Tags: andnoneifischecknotpropertydo
2条回答

使用all()更改if语句:

if all([something1 is not None, 
        check_property(something_else), 
        dr_jekyll is mr_hyde]):
    #do stuff...

根据您的上下文,您可能不需要is not None

>>> a = [1]
>>> if a:
        print "hello, world"


hello, world
>>> if a is not None:
        print "hello, world"


hello, world
>>> 

相关问题 更多 >