Line continuations in python

Breaking up long lines of code in Python

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

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.

Читайте также:  Java class type reference

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.

What comes after Intro to Python?

Intro to Python courses often skip over some fundamental Python concepts.

Sign up below and I’ll explain concepts that new Python programmers often overlook.

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.

Источник

Line Continuation in Python

Line Continuation in Python

  1. Line Continuation With Explicit Line Break in Python
  2. Line Continuation With () in Python

In this tutorial, we will discuss methods for line continuation in Python.

Line Continuation With Explicit Line Break in Python

The \ operator, also known as an explicit line break, can be used to break a single continued long line into many smaller and easy-to-read lines of code. The following code example shows us how we can add a line break for line continuation in Python.

string = "This" + " is" + " a" + " string" \ + " with" + " a" + " double" + " line" + " value"  print(string) 
This is a string with a double line value 

We broke down a long line of strings into two smaller and easy-to-read lines with an explicit line break in the above code. It can also be done with other types of variables, as shown in the example below.

i = 1 + 2 \ + 3  x = 1.1 + 2.2 \ + 3.3  print(i) print(x) 

The only problem with this approach is that it gives the error SyntaxError: unexpected character after line continuation character if there is a blank space after the \ .

Line Continuation With () in Python

Another method that can be used for line continuation is to enclose the lines inside () . The following code example shows us how we can use () for line continuation in Python.

string = ("This" + " is" + " a" + " string" + " with" + " a" + " double" + " line" + " value")  print(string) 
This is a string with a double line value 

In the above code, we broke down a long line of strings into two smaller and easy-to-read lines by enclosing the lines inside the () . This can also be done with other types of variables, as shown in the example below.

i = (1 + 2 + 3)  x = (1.1 + 2.2 + 3.3)  print(i) print(x) 

According to the official Python style guide, the () approach is much more preferable than the explicit line break.

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

Related Article — Python Syntax

Источник

Line continuation | Long statement in Multiple lines in Python

Line continuation | Long statement in Multiple lines in Python

In this article, we will see how to do line continuation when we write a statement or code a long string in python.

In python, we cannot split a line into multiple lines using Enter. Instead, we have to use the backslash ( \ ) to tell python that the next line continues in a new line.

So to let a long string continue on the next line in python, we can

Let’s understand it with some examples.

Using backslash for line continuation in Python

The backslash ( \ ) is the line continuation operator, it tells python that the statement is split into multiple lines. To write the long statement into multiple lines we have to add the backslash at the end of each line.

If we use Enter to go to the next line, it will throw us an error when we run the program.

For example, if we have a long string split into multiple lines using Enter.

str = "Hello, i am a coder I like to write code in python Thank you " print(str) 

Now, when we run the program we get the following output.

File "main.py", line 1 str = "Hello, i am a coder ^ SyntaxError: EOL while scanning string literal 

It throws us the «EOL while scanning string literal» error.

To fix this we can use the backslash at the end of each line. For example.

str = "Hello, i am a coder \ I like to write code in python \ Thank you \ " print(str) 

Now when we run the program, we get

Hello, i am a coder I like to write code in python Thank you 

Here, because of \ at the end of each line, python treats the sentence of each line as one.

We can also use it with integers too for calculation.

add_num = 2+\ 3+\ 4\ print(add_num) 

The output will be the sum of all the numbers.

Using parentheses for line continuation

In python, we can also create a multiline statement using parentheses. We can wrap the statement within the parentheses () to split the statement into multiple lines.

Here, each line should be inside the single ( ‘ ‘ ) and double quotation mark ( » » ).

str = ("Hello, i am a coder " "I like to write code in python " "Thank you") print(str) 

So the output of the program will be.

Hello, i am a coder I like to write code in python Thank you 

The parentheses tell python to print the whole sentence in one line and not to treat it as a multi-line string.

Here, we learned about two methods to do line continuation in python using the backslash and parentheses.

Источник

Оцените статью