How to Break a Long Line to Multiple Lines in Python

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'

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.

How do I split the definition of a long string over multiple lines?

Are you talking about multi-line strings? Easy, use triple quotes to start and end them.

s = """ this is a very
long string if I had the
energy to type more and more ..."""

You can use single quotes too (3 of them of course at start and end) and treat the resulting string s just like any other string.

NOTE: Just as with any string, anything between the starting and ending quotes becomes part of the string, so this example has a leading blank (as pointed out by @root45). This string will also contain both blanks and newlines.

I.e.,:

' this is a very\n        long string if I had the\n        energy to type more and more ...'

Finally, one can also construct long lines in Python like this:

 s = ("this is a very"
"long string too"
"for sure ..."
)

which will not include any extra blanks or newlines (this is a deliberate example showing what the effect of skipping blanks will result in):

'this is a verylong string toofor sure ...'

No commas required, simply place the strings to be joined together into a pair of parenthesis and be sure to account for any needed blanks and newlines.

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

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 can I split up a long f-string in Python?

Use parentheses and string literal concatenation:

msg = (
f'Leave Request created successfully. '
f'Approvers sent the request for approval: {leave_approver_list}'
)

Note, the first literal doesn't need an f, but I include it for consistency/readability.

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 break a long line with multiple bracket pairs?

Using black, the opinionated, reproducible code formatter:

config["network"]["connection"]["client_properties"][
"service"
] = config["network"]["connection"]["client_properties"][
"service"
].format(
service=service
)

How to split one very long line in Pycharm into multiple lines?

Let's try a simple method, if I understand your query correctly. Read the first file, replace commas with newline character, and write the result to the same file.

urlsfile = open('test1.txt', 'r+') # in case you are getting the data from file itself
urls = urlsfile.readline()
urlsfile.close()
newlines = urls.replace(",", "\n") # otherwise replace newlines with the variable name that you are trying to write to the file
newfile = open('test1.txt','w+')
newfile.write(newlines)
newfile.close()

Is it possible to split a sequence of pandas commands across multiple lines?

In python you can continue to the next line by ending your line with a reverse slash or by enclosing the expression in parenthesis.

df.groupby[['x','y']] \
.apply(lambda x: (np.max(x['z'])-np.min(x['z']))) \
.sort_values(ascending=False)

or

(df.groupby[['x','y']]
.apply(lambda x: (np.max(x['z'])-np.min(x['z'])))
.sort_values(ascending=False))


Related Topics



Leave a reply



Submit