3

Style guides prefer line continuation by parenthesis over continuation with backslashes. From PEP 8:

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.

Backslashes may still be appropriate at times. For example, long, multiple with-statements cannot use implicit continuation, so backslashes are acceptable:

with open('/path/to/some/file/you/want/to/read') as file_1, \
     open('/path/to/some/file/being/written', 'w') as file_2:
    file_2.write(file_1.read())

Another such case is with assert statements.

Situations where this is not possible include multiline with-statements and multiline lambda. I just realised another exception is multiline assignment, where parenthesis are a SyntaxError:

(a = b =
 c = d = 42) # SyntaxError

What is the full list of syntax constructs where I cannot use implicit / parenthesis based line continuation as recommended in PEP 8?

This is not specifically addressed in How can I do a line break (line continuation) in Python?.

gerrit
  • 24,025
  • 17
  • 97
  • 170
  • I would say opt for readability and be consistent within a module/package. – wwii Jul 27 '17 at 16:56
  • Parenthesis may be used around expressions only. `with` and `x=y`assignments are statements. – VPfB Jul 27 '17 at 17:10
  • 1
    @VPfB We can write `if (a and \n b):` but not `with (a as aa, \n b as bb):`, and we cannot use parenthesis for multiline lambda, so the expression/statement difference that doesn't seem to be the full story. – gerrit Jul 28 '17 at 09:29

0 Answers0