2

I have a looong statement of "and"'s, for example:

if this == that and this == that and this == that:
    do this

How to correctly break such statements into separate lines, to comply with PEP-8?

2 Answers2

3

PEP8 gives a recommendation:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation. Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it.

and examples:

if (width == 0 and height == 0 and
    color == 'red' and emphasis == 'strong' or
    highlight > 100):
    raise ValueError("sorry, you lose")
if width == 0 and height == 0 and (color == 'red' or
                                   emphasis is None):
    raise ValueError("I don't think so -- values are %s, %s" %
                     (width, height))
Janne Karila
  • 24,266
  • 6
  • 53
  • 94
-1

You can separate lines in Python, but mark them to be the same "semantic" line, by inserting backslashes:

if     this == that \
   and this == that \
   and this == that:
    do this

This will do even if you have and's or or's in your complex conditional expression. Hope this helps.

Baltasarq
  • 12,014
  • 3
  • 38
  • 57
  • 3
    If you have to do that, then use `(...)` parenthesis and avoid the backslashes altogether. `if (this == that and this == that and\n this == that):` – Martijn Pieters May 30 '13 at 08:05
  • 3
    -1 The question is asking for PEP-8 compliance and PEP-8 recommends paranthesis – jamylak May 30 '13 at 08:11