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?.