Python中条件运算符的推荐编码风格是什么?

时间:2015-08-13 12:12:20

标签: python coding-style indentation

以下行是我的代码的一部分。我可能错了,但对我来说似乎是pythonic。然而,初看起来并不清楚它究竟意味着什么。是否有更好的代码布局可以使它更清晰? _idName是一个函数或DataFrame

while  id1!="cancel" and ((id1 not in _idName.id.values) 
        if isinstance(_idName,_pd.DataFrame) else (_idName(id1) is None)):
    do something with the variables evaluated in the condition

2 个答案:

答案 0 :(得分:3)

代码的布局确实使得很清楚发生了什么。

至少,我倾向于在每个the style guide的二元运算符andor之后换行,而不是在单个条件的中间。

我还会尝试在可能的情况下将三元数保持在一条线上;在这种情况下,最终会很长,所以可能不是一个选择。我认为三元组中的布尔运算符在它们的行开头更有意义,虽然我找不到这个的引用(超出"Martijn likes it too")。

一个更可读的例子:

while (id1 != "cancel" and 
       ((id1 not in _idName.id.values) if isinstance(_idName, _pd.DataFrame) 
        else (_idName(id1) is None))):

或者也许:

while (id1 != "cancel" and 
       ((id1 not in _idName.id.values)
        if isinstance(_idName,_pd.DataFrame)
        else (_idName(id1) is None)):

答案 1 :(得分:0)

创建一个小函数来检查你,然后在while语句中使用它。

def check_whatever(id1, _idName):
    if id1 == 'cancel':
        return False

    if isinstance(_idName,_pd.DataFrame):
        return id1 not in _idName.id.values:
    else:
        return _idName(id1) is None


while check_whatever(id1, _idName):
    do_stuff()