How to Do a Line Break (Line Continuation) in Python

How can I do a line break (line continuation) in Python?

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.

Is it possible to break a long line to multiple lines in Python?

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

Example of implicit line continuation:

a = some_function(
'1' + '2' + '3' - '4')

On the topic of line breaks around a binary operator, it goes on to say:

For decades the recommended style was to break after binary operators.
But this can hurt readability in two ways: the operators tend to get scattered across different columns on the screen, and each operator is moved away from its operand and onto the previous line.

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 (line breaks before the operator) is suggested.

Example of explicit line continuation:

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

Breaking a line of python to multiple lines?

Style guide (PEP-8) says:

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. Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it.

Method 1: Using parenthesis

if (number > 5 and
number < 15):
print "1"

Method 2: Using backslash

if number > 5 and \
number < 15:
print "1"

Method 3: Using backslash + indent for better readability

if number > 5 and \
number < 15:
print "1"

How to create a linebreak after line continuation symbol (\)

Try adding more slashes:

>>> A = """line 1 \\
line 2 \\
line 3"""
>>> print(A)
line 1 \
line 2 \
line 3
>>>

Or escape it with r"":

>>> A = r"""line 1 \
line 2 \
line 3"""
>>> print(A)
line 1 \
line 2 \
line 3
>>>

r means the string is a raw string. So the text in it will be escaped.

how to break a long line of chained assignments in python

As a single statement, there are no subexpressions to parenthesize. I'm not a fan of explicit line continuations, but this is probably a case where it looks least bad (maybe because the variables names are still probably shorter than other lines you might be breaking).

long_variable_name = \
another_long_name = \
a_third_name = some_func()

I don't know if you would want to put the function call on a line by itself or not.

If you really want to avoid explicit line breaking, I'd recommend not chaining the assignments in the first place.

long_variable_name = some_func()
another_long_name = long_variable_name
a_third_name = long_variable_name

You might try tuple unpacking. It looks a bit hackish IMO, but ...

(long_variable_name,
another_long_name,
a third_name) = (some_func(),)*3

At the cost of a little more runtime overhead, you could use itertools.repeat:

from itertools import repeat

(long_variable_name,
another_long_name,
a third_name) = repeat(some_func(), 3)

although both approaches make you specify the number of variables being assigned too. Although you can capture the remainder of a finite sequence in a catch-all variable during tuple unpacking, I'm not aware of a similar trick for infinite sequences.

# Good
v1, v2, v3, *rest = repeat(some_func(), 100)

# Bad - infinite loop
v1, v2, v3, *rest = repeat(some_func())

Correct style for line breaks when chaining methods in Python

PEP 8 recommends using parenthesis so that you don't need \, and gently suggests breaking before binary operators instead of after them. Thus, the preferred way of formatting you code is like this:

my_var = (somethinglikethis
.where(we=do_things)
.where(we=domore)
.where(we=everdomore))

The two relevant passages are this one from the Maximum Line Length section:

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.

... and the entire Should a line break before or after a binary operator? section:

Should a line break before or after a binary operator?

For decades the recommended style was to break after binary operators.
But this can hurt readability in two ways: the operators tend to get
scattered across different columns on the screen, and each operator is
moved away from its operand and onto the previous line. Here, the eye
has to do extra work to tell which items are added and which are
subtracted:

# No: operators sit far away from their operands
income = (gross_wages +
taxable_interest +
(dividends - qualified_dividends) -
ira_deduction -
student_loan_interest)

To solve this readability problem, mathematicians and their publishers
follow the opposite convention. 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"

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.

Note that, as indicated in the quote above, PEP 8 used to give the opposite advice about where to break around an operator, quoted below for posterity:

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

How to write long arithmetic expressions in several lines in python?

I hate backslashes, so I prefer to enclose the right hand side in parens, and break/indent on the top-level operators:

new_matrix[row][element] = (old_matrix[top_i][top_j]
+ old_matrix[index_i][element]
+ old_matrix[row][index_j]
+ old_matrix[row][index_j])

How do I add a line-break to a multiple assignment statement?

I could do it eventually by adding brackets as follows:

(a1, a2, ................a30,
a31, a32, ..............a60) = get_values()

How to add a line break in python?

You can print new line characters:

print('\n'*numlines)


Related Topics



Leave a reply



Submit