How do you break a long line 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. 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

4 minute read Python 3.7—3.10

How do you break a long line in python?

Watch as video

03:01

Sign in to your Python Morsels account to save your screencast settings.

Don't have an account yet? Sign up here.

Let's talk about breaking up long lines of code in Python.

How to continue code on the next line

The import statement below is longer than I'd like for a single continuous line:

from collections.abc import Hashable, Iterable, KeysView, Mapping, MutableMapping, Set

Note from Trey: I often use a maximum line length of 79 characters in my projects (though this really varies from project to project).

We could break this line into two by putting a backslash (\) at the end of the line and then pressing the Enter key:

from collections.abc import Hashable, Iterable, KeysView, Mapping, \
        MutableMapping, Set

This is a way of telling Python that the first line of code continues onto the next line. This works in Python but it's not recommended.

Instead, the Python style guide (PEP 8) recommends using implicit line continuation. An implicit line continuation happens whenever Python gets to the end of a line of code and sees that there's more to come because a parenthesis ((), square bracket ([) or curly brace ({) has been left open.

So adding parenthesis (( and )) to this line will allow us to put newlines wherever we want inside those parentheses:

from collections.abc import (
    Hashable,Iterable, KeysView, Mapping,
        MutableMapping, Set)

Alignment is a personal preference

When wrapping code over multiple lines, some Python programmers prefer to line up their code visually like this:

from collections.abc import (Hashable, Iterable, KeysView, Mapping,
                             MutableMapping, Set)

But some Python programmers instead put each item on its own line:

from collections.abc import (
    Hashable,
    Iterable,
    KeysView,
    Mapping,
    MutableMapping,
    Set,
)

However you choose to break your lines up, know that within parentheses you can put line breaks wherever you want in your code and you could put whatever whitespace you'd like inside parentheses:

from collections.abc import (Hashable,
    Iterable, KeysView, Mapping,
                             MutableMapping, Set)

That strange spacing above works because this isn't indentation, it's alignment. Python treats white space within those parentheses as the same as it would treat whitespace in the middle of any other line of code.

It's a matter of personal preference how you wrap your code. You can look at PEP 8 for some ideas.

Function calls already have parentheses

What if you want to wrap a function call over multiple lines?

Inside a function call (like print below) we already have parentheses:

fruits = ["lemons", "pears", "jujubes", "apples", "bananas", "blueberries", "watermelon"]

print("I like", " and ".join(sorted(fruits)), "but I only like certain types of pears")

We don't need to add extra parentheses. We can add line breaks wherever we want in a function call and it pretty much just works:

fruits = ["lemons", "pears", "jujubes", "apples", "bananas", "blueberries", "watermelon"]

print(
    "I like",
    " and ".join(sorted(fruits)),
    "but I only like certain types of pears")

Implicit line continuations work for all kinds of brackets and braces

The same rule applies to square brackets ([]).

If we want to break up a long list over multiple lines:

fruits = ["lemons", "pears", "jujubes", "apples", "bananas", "blueberries", "watermelon"]

We can add line breaks wherever we'd like within that list:

fruits = [
    "lemons",
    "pears",
    "jujubes",
    "apples",
    "bananas",
    "blueberries",
    "watermelon",
]

As long as we have an open square bracket ([), parenthesis ((), or an open curly brace ({), we can add line breaks wherever we'd like within those brackets or braces.

Which means we could take this dictionary:

days = {"Monday": "Mon", "Tuesday": "Tues", "Wednesday": "Wed", "Thursday": "Thurs", "Friday": "Fri", "Saturday": "Sat", "Sunday": "Sun"}

And break it up over multiple lines by putting line breaks after each element:

days = {
    "Monday": "Mon",
    "Tuesday": "Tues",
    "Wednesday": "Wed",
    "Thursday": "Thurs",
    "Friday": "Fri",
    "Saturday": "Sat",
    "Sunday": "Sun",
}

Code auto-formatters can help

You don't have to do this on your own. You could choose to use a code formatter, like black, to do this work for you:

$ black -l 79 abbreviations.py
reformatted abbreviations.py
All done! ✨ 🍰 ✨
1 file reformatted.

However you do choose to break your code over multiple lines, remember that it's all about the brackets ([]) and the braces ({} and ()): that's what allows for implicit line continuation.

Summary

If you have a very long line of code in Python and you'd like to break it up over over multiple lines, if you're inside parentheses, square brackets, or curly braces you can put line breaks wherever you'd like because Python allows for implicit line continuation.

If you don't have brackets or braces on your line yet, you can add parentheses wherever you'd like and then put line breaks within them to format your code nicely over multiple lines.

Series: Overlooked Fundamentals

These topics are commonly overlooked by new Python programmers.

To track your progress on this Python Morsels topic trail, sign in or sign up.

A Python Tip Every Week

Need to fill-in gaps in your Python skills? I send weekly emails designed to do just that.

How do you break a long line of code?

Use backslashes to break up a long line of code In cases where implied line continuation is not an option, use backslashes. For example, assert or with statements should be split with backslashes. Warning: No characters can follow a backslash when it is used as a line break, including whitespace and in-line comments.

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

Breaking Long Lines of Code in Python It is recommended not to have lines of code longer than 79 characters. Python supports implicit line continuation. This means any expression inside the parenthesis, square brackets, or curly braces can be broken into multiple lines.

How do you break a line in print Python?