if, continuation and indentation

Jean-Michel Pichavant jeanmichel at sequans.com
Fri May 28 06:34:54 EDT 2010


Jonathan Hartley wrote:
> On May 27, 1:57 pm, Jean-Michel Pichavant <jeanmic... at sequans.com>
> wrote:
>   
>> HH wrote:
>>     
>>> I have a question about best practices when it comes to line wrapping/
>>> continuation and indentation, specifically in the case of an if
>>> statement.
>>>       
>>> When I write an if statement with many conditions, I prefer to use a
>>> parenthesis around the whole block and get the implicit continuation,
>>> rather than ending each line with an escape character.  Thus, using
>>> the example from the style guide (http://www.python.org/dev/peps/
>>> pep-0008/) I would write:
>>>       
>>>     if (width == 0 and
>>>         height == 0 and
>>>         color == 'red' and
>>>         emphasis == 'strong' or
>>>         highlight > 100):
>>>         raise ValueError("sorry, you lose")
>>>       
>>> The problem should be obvious -- it's not easy to see where the
>>> conditional ends and the statement begins since they have the same
>>> indentation.  Part of the problem, I suppose, is that Emacs indents
>>> 'height' and the other lines in the conditional to 4 spaces (because
>>> of the parenthesis).  How do people deal with this situation?
>>>       
>>> Thanks,
>>> Henrik
>>>       
>> One possible solution
>>
>>     if (
>>             width == 0 and
>>             height == 0 and
>>             color == 'red' and
>>             emphasis == 'strong' or
>>             highlight > 100
>>        ):
>>         raise ValueError("sorry, you lose")
>>
>> JM  
>>     
>
> I've always liked this, or even:
>
>   if (
>       width == 0 and
>       height == 0 and
>       color == 'red' and
>       emphasis == 'strong' or
>       highlight > 100
>   ):
>       raise ValueError("sorry, you lose")
>
>
> but my co-workers have uniformly gone bananas whenever I try it.
>   
I tried to give a layout that fits the OP way of doing, but I would not 
use what I described above, so I can understand why your co workers go 
bananas :)

when it comes to extended conditions in if statement I prefer to write 
something like

if self.haveLost():
    raise ValueError("sorry, you lose")

It drastically improves the reading because it splits the notion of what 
to do in which case, and how do you identify the cases (i.e. what should 
I do when I've lost, and how do I know that I've lost). If you don't 
want to pollute your upper namespace you can embed the function that way:

def foo():
    width = 0
    height = 0
    color = 'red'
    emphasis = 'strong'

    def haveLost():
        return not width and not height and color == 'red' and emphasis 
=='strong'

    if haveLost():
        raise ValueError("sorry you lose")

It has the cool side effect to name your condition as well, that helps 
debugging the condition *a lot*.

JM



More information about the Python-list mailing list