1352

Given:

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

How do I write the above in two lines?

e = 'a' + 'b' +
    'c' + 'd'
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Ray
  • 187,153
  • 97
  • 222
  • 204

10 Answers10

1522

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):

or with explicit line break:

if a == True and \
   b == False:

Check the style guide for more information.

Using parentheses, your example can be written over multiple lines:

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

The same effect can be obtained using explicit line break:

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.

0 _
  • 10,524
  • 11
  • 77
  • 109
Harley Holcombe
  • 175,848
  • 15
  • 70
  • 63
  • 49
    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
  • I think it's saying that if you have brackets around an expression already, use those, but don't put brackets around an expression just for the purpose of breaking it over multiple lines. No hard-and-fast rule though. I do think for the line in the question though, a backslash is the way to go. – Harley Holcombe Sep 11 '08 at 22:59
  • That's not correct. Please edit your answer to reflect what the style guide actually says, rather than stating the opposite. – Carl Meyer Sep 21 '08 at 18:26
  • 39
    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 02:33
  • 3
    Jerub: you disagree with Carl, but you quote the guide stating that "The preferred way… is by using Python's implied line continuation inside parentheses…". So you either disagree with Harley, or you lost the meaning of the quote you pasted. – tzot Oct 10 '08 at 00:57
  • 2
    The thing is, in this case there are _no_ parentheses required. Sure, you can have them, but why would you put them around the example in the question? Either way, I'll edit my answer slightly to clarify. – Harley Holcombe Oct 10 '08 at 01:08
  • 18
    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
  • 38
    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 08 '12 at 09:04
  • 1
    @HarleyHolcombe I read that as it being acceptable to add parentheses in order to wrap long lines; if the expressions already had parentheses there would be no need to wrap it. However, it's definitely not 100% clear and I won't quibble over interpretation. The deciding factor for me is that I think it looks better that way :). – Daniel Feb 09 '12 at 00:54
  • 64
    PEP8 did indeed change in 2010 - "sometimes using a backslash looks better" has gone. – e100 Mar 18 '12 at 18:31
  • 11
    @e100 _"Backslashes may still be appropriate at times."_ is there now in 2014. Dunno if it was gone and then came back or just moved. – matt wilkie Oct 09 '14 at 16:34
  • 1
    Not super important but because it python I would recomend using `(spam + eggs + foo + bar + moreSpam + moreEggs)` because in python spam and eggs are traditional. – tox123 Oct 25 '14 at 01:12
  • 2
    so if you chain you should use parens around your line breaking chains? i'm pretty frustrated with python coming from c, c++, c# and javascript. Its not as simple as I expected because whitespace does matter, thinking this was less is more but they got me. – King Friday Oct 17 '15 at 00:57
  • What to do with `ans['Interfaces Declared by Environment'][env_.name][interface_] = None`? This line is too long, but I don't know where to split! – nerdoc Jan 21 '16 at 16:00
  • My IDE yells at me if I have a hanging indent aligned with an indented code block underneath it. In these cases I frequently remove parentheses and replace them with backslashes so there is a one-character gap. – Darren Ringer Aug 03 '16 at 19:25
  • 11
    Advantage of the parenthesised version: you can put comments after the line break. I often use multiline statements to break a single statement into pieces and comment on each piece. Can't to that with the backslashes. – Peter Feb 24 '17 at 18:03
  • Very confusing apparently in the specific case of using `+` string concatenation, normal hanging indent does not work... you MUST (?) enclose the whole thing in parens. E.g.: `1: a = 'this ' + does +` `2: ' not ' + work` must be written as `1: a = ('this ' + does +` `2: ' work ' + fine)`. Jeeez – user9645 Oct 27 '20 at 15:15
  • If anyone's wondering where backslash must be used instead of parenthesis: with the `assert` keyword. https://stackoverflow.com/a/3112178/5629418 – Roland Weber Jun 30 '21 at 12:16
  • @Peter If to make a line of code comprehensible, you need to break it up into multiple lines and put a comment after each, it's a bad sign. Prefer splitting complex statements into multiple statements, using clear variable names, etc. Make the code speak for itself, and you can avoid line-by-line comments almost entirely. – MarredCheese Sep 24 '21 at 03:10
304

From PEP 8 -- 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)file_2.write(file_1.read())

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

S.B
  • 13,077
  • 10
  • 22
  • 49
jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • 4
    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
  • 10
    But note that "sometimes using a backslash looks better" has gone too. – e100 Mar 18 '12 at 00:04
  • 1
    @e100: here're [three](http://stackoverflow.com/a/26435241/4279) [code](http://stackoverflow.com/a/26399211/4279) [examples](http://stackoverflow.com/a/26370717/4279) where backslashes make the code more readable: [*"sometimes the style guide just doesn't apply. When in doubt, use your best judgment."*](http://legacy.python.org/dev/peps/pep-0008/#a-foolish-consistency-is-the-hobgoblin-of-little-minds) – jfs Oct 23 '14 at 03:27
  • 7
    In 2015 the style guide was updated to actually prefer breaking **before** binary operators after research by [Donald Knuth](https://mail.python.org/pipermail/python-dev/2016-April/144205.html) due to the perceived improvements in readability. – J2C Jul 08 '16 at 11:04
89

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.

Ted Pudlik
  • 665
  • 8
  • 26
George V. Reilly
  • 15,885
  • 7
  • 43
  • 38
  • 11
    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 01 '11 at 19:07
  • 1
    It is not only true for the space after the backslash. backslash should be strictly the last character in the line. In particular you cannot comment specific terms in a sum by breaking the line with backslash and putting a comment after it. Brackets work fine! :) – Roux Aug 20 '21 at 15:46
  • It is a pity that this explanation disappeared from the documentation (after 3.1). In PEP8 the reasoning is not explained. – pabouk - Ukraine stay strong Mar 14 '22 at 08:47
41

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)
SCdF
  • 57,260
  • 24
  • 77
  • 113
30

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
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
27

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.

Jason Navarrete
  • 7,495
  • 6
  • 28
  • 22
  • 7
    -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 08 '09 at 18:18
22

If you want to break your line because of a long literal string, you can break that string into pieces:

long_string = "a very long string"
print("a very long string")

will be replaced by

long_string = (
  "a "
  "very "
  "long "
  "string"
)
print(
  "a "
  "very "
  "long "
  "string"
)

Output for both print statements:

a very long string

Notice the parenthesis in the affectation.

Notice also that breaking literal strings into pieces allows to use the literal prefix only on parts of the string and mix the delimiters:

s = (
  '''2+2='''
  f"{2+2}"
)
jlaurens
  • 529
  • 5
  • 10
13

One can also break the call of methods (obj.method()) in multiple lines.

Enclose the command in parenthesis "()" and span multiple lines:

> res = (some_object
         .apply(args)
         .filter()
         .values)

For instance, I find it useful on chain calling Pandas/Holoviews objects methods.

Brandt
  • 5,058
  • 3
  • 28
  • 46
8

It may not be the Pythonic way, but I generally use a list with the join function for writing a long string, like SQL queries:

query = " ".join([
    'SELECT * FROM "TableName"',
    'WHERE "SomeColumn1"=VALUE',
    'ORDER BY "SomeColumn2"',
    'LIMIT 5;'
])
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hardik Sondagar
  • 4,347
  • 3
  • 28
  • 48
4

Taken from The Hitchhiker's Guide to Python (Line Continuation):

When a logical line of code is longer than the accepted limit, you need to split it over multiple physical lines. The Python interpreter will join consecutive lines if the last character of the line is a backslash. This is helpful in some cases, but should usually be avoided because of its fragility: a white space added to the end of the line, after the backslash, will break the code and may have unexpected results.

A better solution is to use parentheses around your elements. Left with an unclosed parenthesis on an end-of-line the Python interpreter will join the next line until the parentheses are closed. The same behaviour holds for curly and square braces.

However, more often than not, having to split a long logical line is a sign that you are trying to do too many things at the same time, which may hinder readability.

Having that said, here's an example considering multiple imports (when exceeding line limits, defined on PEP-8), also applied to strings in general:

from app import (
    app, abort, make_response, redirect, render_template, request, session
)
Community
  • 1
  • 1
ivanleoncz
  • 9,070
  • 7
  • 57
  • 49