考虑这段代码:
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/