Line too long python как перенести
Перейти к содержимому

Line too long python как перенести

  • автор:

Breaking up long lines of code in Python

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:

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:

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:

Alignment is a personal preference

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

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

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:

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:

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:

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:

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

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:

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

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:

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.

Breaking long lines in Python

In some of the programs discussed in the book including the sample solutions, you will see statements like:

This is really the following single statement:

The first code snippet above is an example of breaking a long line into two (or more) lines so that we don’t end up with really long lines in our code. How long should a line be when you should think about breaking it? If your statement’s length is more than 80 characters, you should think about breaking it up.

In the book, we often had to do so because of layout reasons even though the statement may not have exceeded 80 characters, and in your projects you will want to do it so that your statements are easier to read and on the average all lines have a similar length. This is formalized (among other things) in PEP 8.

Note that the examples below will for illustrative purposes break lines waaaaay less than 80 characters.

How do you break?

When not calling function

When you are not calling a function, you essentially have two choices:

Use paranthesis

This is exactly how we break the long statement in the example we started this article with. For the moment ignore the call to print() and assume that the statement is:

This essentially just creates the string s. If we were to split this statement over multiple lines, we would do the following:

Note the extra beginning and the ending parenthesis.

Here is another example:

Here is how we can use split the above statment into multiple lines using parentheses:

Use the line continuation operator

The line continuation operator, \ can be used to split long statements over multiple lines. Here is how we could split the above statement using \ instead:

At the end of every line (except the last), we just add a \ indicating that the next line is also a part of the same statement.

Breaking up those long if statements

Often I have to break long if statements and is in fact one of the most common cases I face at work where I have to break the statement into multiple lines. Here is an example using both the approaches above:

When calling functions

By default, when calling functions you can just press enter and without doing anything more keep writing your statement over multiple lines. For example:

Hence, we could have broken the first example we saw as:

When calling format() we put the arguments over separate lines.

Learning more about Python coding style

If you liked reading this article, you may also find it worth your time going over the Python style guide. You may even find instances where I have not followed a guideline when writing the programs in the book. If you find one, let me know.

How can I break up this long line in Python? [duplicate]

How would you go about formatting a long line such as this? I’d like to get it to no more than 80 characters wide:

Is this my best option?

6 Answers 6

That’s a start. It’s not a bad practice to define your longer strings outside of the code that uses them. It’s a way to separate data and behavior. Your first option is to join string literals together implicitly by making them adjacent to one another:

Or with line ending continuations, which is a little more fragile, as this works:

But this doesn’t:

See the difference? No? Well you won’t when it’s your code either.

(There’s a space after \ in the second example.)

The downside to implicit joining is that it only works with string literals, not with strings taken from variables, so things can get a little more hairy when you refactor. Also, you can only interpolate formatting on the combined string as a whole.

Alternatively, you can join explicitly using the concatenation operator ( + ):

Explicit is better than implicit, as the zen of python says, but this creates three strings instead of one, and uses twice as much memory: there are the two you have written, plus one which is the two of them joined together, so you have to know when to ignore the zen. The upside is you can apply formatting to any of the substrings separately on each line, or to the whole lot from outside the parentheses.

Finally, you can use triple-quoted strings:

This is often my favorite, though its behavior is slightly different as the newline and any leading whitespace on subsequent lines will show up in your final string. You can eliminate the newline with an escaping backslash.

This has the same problem as the same technique above, in that correct code only differs from incorrect code by invisible whitespace.

Which one is "best" depends on your particular situation, but the answer is not simply aesthetic, but one of subtly different behaviors.

How to deal with long lines of code and commands in Python

Is it that the line should always be less than 80 chars, even if it is spanning multiple lines? PEP 8, the style guide for code included in the Python standard library, suggests that the most important consideration for continuation lines is to ensure that they are easily distinguished from indented lines (those starting a new block).

How to deal with long lines of code and commands in Python

I've tried searching, but I couldn't find any situations similar to mine. I am writing a program and so far I've stuck to the no more than 79 characters in a line rule. However I'm not sure where to break lines in a few situations.

Here are the problem areas:

For this situation when I break first line after the '(SayText "%s")\n', the second line ends up being 80 characters long. Should I then break the second line somewhere in the brackets like this?

Or would it be better to bring the entire third line to the beginning of the first brackets like this:

Another example of this is here:

Should I do this?

What would be a good convention to follow?

Solution 1:

In my opinion, one of the reasons to prefer shorter lines is that it makes the programmer more likely to break up code into individual shorter lines which are easier to understand and to spot errors or better ways to do things in.

For your second example:

Solution 2:

Whatever works for you or the conventions of the code base you are working on. PEP 8, the style guide for code included in the Python standard library, suggests that the most important consideration for continuation lines is to ensure that they are easily distinguished from indented lines (those starting a new block).

See the examples given there.

Solution 3:

A convention I sometimes follow when the usual indentation style leads to too much horror, is the following:

It looks very weird at first. But it clearly lays out the "head" of the multi-line structure separately on the first line where it is prominent, and clearly shows where the multi-line structure stops. Only indenting one level, instead of to the level of the opening brace, gives you a lot more room to write the nested lines. And it has the happy side effect of causing diffs to clearly show when you only change the arguments of such a call, which is occasionally helpful.

In some ways I think this formatting convention is actually a better fit for modern high level OO languages than the usual styles, which tend to date back to C; C doesn't have chained calls and tended to have much shorter callable names due to not having objects. But since no one else uses this style I save it as a fallback for when the normal style makes readability worse.

Solution 4:

As a general rule, I try to break at the first point in the "dominant" syntactic connective, and use a single indent for the continuation line for a normal statement, or a double indent if the broken line is followed by a colon. However, if the syntactic connective is "." then I prefer to use temporary variables, as this is usually more clear.

For your examples:

For function calls with many arguments, I sometimes find it most clear to put one on a line, even if more could fit. E.g.

The variation on this for ":" terminated statements is illustrated:

but usually clearer would be

A final note: some people consider these rules obsolete, as you can usually use a larger window. I find these rules quite useful, still, because:

  • with consistently short lines I can see code in more open windows (or more editing panes)
  • the method above exhibits the logical structure of the program
  • when it isn't easy to break lines, it is often a sign that the structure would be better exhibited with temporary variables (etc.)

When a line of codes is too long, how do I break up the line without \

I have created a few of classes, but these classes have names that are too long (eq: NegativeChannelMetalOxideSemiconductorFieldEffectTransistor ). I want to make a new line with \ in python, but in this case it is ugly. In general in Python, when code is too long, using \ to make a new line is a good choice, but it will not work here. How should I shorten or break up these lines?

figure1

figure3

Solution:

Some suggestions on shortening this line without a \ :

You can break a line inside of braces [] , <> , () without using a \ .

You can use acronyms or abbreviations:

Python: Black doesn't wrap long lines

I am using black==20.8b1 .

I have a long string like:

Why is the string not wrapped? I thought that black supports wrapping strings now (based on issues in github).

Solution 1:

Currently we have to add —experimental-string-processing tag to it. I think in future versions it will be made default.

Solution 2:

Currently, Black doesn't wrap long strings or long comments. You can see an open issue in their project GitHub saying:

Black currently doesn't wrap long string literals or merge string literals that happen to be on the same line. [. ] It would require modifying the AST which isn't 100% safe and has a bunch of edge cases to be dealt with.

Solution 3:

Since 22.1.0, you have to run Black with —preview .

Linter "line too long" error and excessive whitespace inside multi-line strings in ST3

So there are two problems. I have this chunk of code in Sublime Text 3, where I use Anaconda package (relevant whitespace will be shown as • , as it is displayed in ST3; Python.sublime-settings are shown at the end of this post):

First problem:
I have Word Wrap enabled and the ruler set at 80, so it wraps the code automatically, having exactly 79 characters on the line with "print. " and 1 character on the next line. But linter gives me an error "[W] PEP8 (E501): line too long (80 > 79 characters)". I have right parentheses auto-indented on the next line, so there is no violation of the "79 characters per line" rule. What could be the problem here? Is it that the line should always be less than 80 chars, even if it is spanning multiple lines?

Here I wanted to get rid of the ">79 characters" error and make a multi-line string. The thing is, when I split two sentences in the string over two lines to be able to align them according to PEP8 rules, I have to indent them, and indentation means excessive whitespace inside the string, which is not what I want. Here's how it should work ideally, with a needed space character right after the end of the first sentence, and no whitespace used to indent the second half of the string:

Solution:

You can make use of Python string concat mechanisms and write the string in single quotes as seen in the example:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *