Breaking up long lines of code in Python

Transcript

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

How to continue code on the next line

Let's say 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",
}

You could a code formatter to do this for you

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.