带有长 if 谓词的 Python 风格

标签 python coding-style formatting styles pep8

考虑这段代码:

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 的规范解决方案可以提高上面列出的方法的可读性?

最佳答案

使用 all() 更改 if 语句:

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

关于带有长 if 谓词的 Python 风格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19981513/

相关文章:

java - 如何从检查操作中排除某些文件

python - 通过引用传递 pandas DataFrame

python - 无法在 python selenium 中加载 firefox 附加组件

debugging - 如何在 OCaml 中跟踪程序进行调试?

scala - Intellij Scala 多种导入样式格式设置

r - 如何在 R 中格式化数字,指定有效位数但保留有效零和整数部分?

python - Flask-Migrate "No section: ' alembic '"on "db migrate”命令

python - ModelAdmin 查询集中跨多个表的 Django 聚合

开放流 try/finally block 的 Java 代码风格

javascript - 如何使用变量名实现字符串格式化程序