how to format long if conditions

Colin J. Williams cjw at ncf.ca
Sat Aug 27 11:16:51 EDT 2011


On 27-Aug-11 03:50 AM, Hans Mulder wrote:
> On 27/08/11 09:08:20, Arnaud Delobelle wrote:
>> I'm wondering what advice you have about formatting if statements with
>> long conditions (I always format my code to<80 colums)
>>
>> Here's an example taken from something I'm writing at the moment and
>> how I've formatted it:
>>
>>
>> if (isinstance(left, PyCompare) and isinstance(right, PyCompare)
>> and left.complist[-1] is right.complist[0]):
>> py_and = PyCompare(left.complist + right.complist[1:])
>> else:
>> py_and = PyBooleanAnd(left, right)
>>
>> What would you do?
>
> I would break after the '(' and indent the condition once and
> put the '):' bit on a separate line, aligned with the 'if':
>
>
> if (
> isinstance(left, PyCompare)
> and isinstance(right, PyCompare)
> and left.complist[-1] is right.complist[0]
> ):
> py_and = PyCompare(left.complist + right.complist[1:])
> else:
> py_and = PyBooleanAnd(left, right)
>
> It may look ugly, but it's very clear where the condition part ends
> and the 'then' part begins.
>
> -- HansM

What about:
           cond=  isinstance(left, PyCompare)
                  and isinstance(right, PyCompare)
                  and left.complist[-1] is right.complist[0]
           py_and= PyCompare(left.complist + right.complist[1:])if cond
                   else: py_and = PyBooleanAnd(left, right)
Colin W.



More information about the Python-list mailing list