I have a long line of code that I want to break up among multiple lines. What do I use and what is the syntax?

For example, adding a bunch of strings,

e = 'a' + 'b' + 'c' + 'd'

and have it like this:

e = 'a' + 'b' +
    'c' + 'd'
share|improve this question
up vote 795 down vote accepted

What is the line? You can just have arguments on the next line without any problems:

a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5, 
            blahblah6, blahblah7)

Otherwise you can do something like this:

if a == True and \
   b == False

Check the style guide for more information.

From your example line:

a = '1' + '2' + '3' + \
    '4' + '5'

Or:

a = ('1' + '2' + '3' +
    '4' + '5')

Note that the style guide says that using the implicit continuation with parentheses is preferred, but in this particular case just adding parentheses around your expression is probably the wrong way to go.

share|improve this answer
25  
Actually, you have the style guide's preference exactly backwards. Implicit continuation is preferred, explicit backslash is to be used only if necessary. – Carl Meyer Sep 11 '08 at 19:00
27  
Carl: I disagree, this is from the guide: The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. – Jerub Sep 22 '08 at 2:33
12  
The key part of the style guide quote is "If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better." The style guide is not saying that you should add parentheses, it leaves it to the judgement of the writer. – Tony Meyer Nov 13 '08 at 22:49
16  
Presumably PEP-8 has changed since these comments were added, as it's fairly clear now that parentheses should be added to wrap long lines: "Long lines can be broken over multiple lines by wrapping expressions in parentheses." – Daniel Feb 8 '12 at 9:04
35  
PEP8 did indeed change in 2010 - "sometimes using a backslash looks better" has gone. – e100 Mar 18 '12 at 18:31

From Style Guide for Python Code:

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.

Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it. Some examples:

class Rectangle(Blob):

    def __init__(self, width, height,
                 color='black', emphasis=None, highlight=0):
        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))
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)

EDIT: PEP8 now recommends the opposite convention (for breaking at binary operations) used by Mathematicians and their publishers to improve readability.

Donald Knuth's style of breaking before a binary operator aligns operators vertically, thus reducing the eye's workload when determining which items are added and subtracted.

From PEP8: Should a line break before or after a binary operator?:

Donald Knuth explains the traditional rule in his Computers and Typesetting series: "Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations"[3].

Following the tradition from mathematics usually results in more readable code:

# Yes: easy to match operators with operands
income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)

In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth's style is suggested.

[3]: Donald Knuth's The TeXBook, pages 195 and 196

share|improve this answer
2  
NB the recommendation changed in 2010: "Long lines can be broken ... by wrapping expressions in parentheses. These should be used in preference to using a backslash...", and all backslashes were removed from the code example. – e100 Mar 17 '12 at 20:33
1  
@e100: read the text in bold above: The preferred way .. is by using Python's implied line continuation inside parentheses it is the same thing as by wrapping expressions in parentheses. I've updated example – jfs Mar 17 '12 at 21:23
9  
But note that "sometimes using a backslash looks better" has gone too. – e100 Mar 18 '12 at 0:04
1  
@e100: here're three code examples where backslashes make the code more readable: "sometimes the style guide just doesn't apply. When in doubt, use your best judgment." – jfs Oct 23 '14 at 3:27
2  
In 2015 the style guide was updated to actually prefer breaking before binary operators after research by Donald Knuth due to the perceived improvements in readability. – J2C Jul 8 '16 at 11:04

The danger in using a backslash to end a line is that if whitespace is added after the backslash (which, of course, is very hard to see), the backslash is no longer doing what you thought it was.

See Python Idioms and Anti-Idioms (for Python 2 or Python 3) for more.

share|improve this answer
5  
This is one reason that it's nice to be able to see trailing whitespace better; i.e. something like set list listchars=trail:· in vim. :) – Beau Feb 1 '11 at 19:07

You can break lines in between parenthesises and braces. Additionally, you can append the backslash character \ to a line to explicitly break it:

x = (tuples_first_value,
     second_value)
y = 1 + \
    2
share|improve this answer

Put a \ at the end of your line or enclose the statement in parens ( .. ). From IBM:

b = ((i1 < 20) and
     (i2 < 30) and
     (i3 < 40))

or

b = (i1 < 20) and \
    (i2 < 30) and \
    (i3 < 40)
share|improve this answer

From the horse's mouth: Explicit line joining

Two or more physical lines may be joined into logical lines using backslash characters (\), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line character. For example:

if 1900 < year < 2100 and 1 <= month <= 12 \
   and 1 <= day <= 31 and 0 <= hour < 24 \
   and 0 <= minute < 60 and 0 <= second < 60:   # Looks like a valid date
        return 1

A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.

share|improve this answer
6  
-1 because the example is unidiomatic IMO. Compound conditionals can absolutely have enclosing brackets instead, which is more practical (for editing or automatic rewrapping) and idiomatic. – u0b34a0f6ae Dec 8 '09 at 18:18
    
Your link is broken. – MarianD Jul 23 at 23:40

protected by NullPoiиteя Oct 10 '13 at 8:04

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.