tags:

views:

16911

answers:

8

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'

have it like this:

e = 'a' + 'b' 
+ 'c' + 'd'
+3  A: 

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
+27  A: 

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 somthing like this:

if a = True and \
   b = False

Check the Style Guide for more info.

(edit)

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.

Harley
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
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
That's not correct. Please edit your answer to reflect what the style guide actually says, rather than stating the opposite.
Carl Meyer
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
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.
ΤΖΩΤΖΙΟΥ
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
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
A: 

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
-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.
kaizer.se
+14  A: 

@Harley

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. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. 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)
J.F. Sebastian
+9  A: 

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

George V. Reilly
+11  A: 

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

Style guide is just a guide. Do it however you prefer to do it.

gbsmith
Though of course it looks better with parentheses than with backslashes. (Personally, on a german keyboard, parens are lots easier to type... ;-))
jae
A: 

@all If Tony's point on slashes sometimes looking better (early in the PEP) overrules the latter parts about parens, then why are parens being mandated (and non-parens being deprecated) in Py3k, i.e. the forms raise ValueError('message') print("whatever")

at least the latter one just seems like extra typing.

zanpaktou