Long code lines 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.

Читайте также:  Python reverse shell online

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.

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.

Источник

How to Break Long Lines in Python

Python supports implicit line continuation. This means you can break long lines of code.

For example, instead of this:

math_students = ["Alice", "Bob", "Charlie", "David", "Emmanuel"]

You can write it like this:

math_students = [ "Alice", "Bob", "Charlie", "David", "Emmanuel" ]

As a matter of fact, you should limit all lines of code to a maximum of 79 characters.

Today, you are going to learn when and how to break long lines in Python.

Breaking Long Lines of Code in Python

Breaking lines increases the total number of lines of code. But at the same, it can drastically improve the readability of your code.

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.

For example, here is a long print() function call is broken into multiple lines in a couple of ways:

print("Alice", "Bob", "Charlie", "David", "Emmanuel", "Farao", "Gabriel", "Hilbert", "Isaac") print( "Alice", "Bob", "Charlie", "David", "Emmanuel", "Farao", "Gabriel", "Hilbert", "Isaac" ) print( "Alice", "Bob", "Charlie", "David", "Emmanuel", "Farao", "Gabriel", "Hilbert", "Isaac" )

There are many ways you can break long lines in Python. You may want to check the official style guide that explains best practices more thoroughly.

Before jumping into examples, notice that there is a way to automatize the line-breaking process.

How to Auto-Break Long Lines of Code in Python

Popular code editors allow you install plugins that enforce code style guidelines.

A cool feature of these plugins is you can usually auto-format code. In other words, the plugin automatically takes care no line exceeds the 79 character “limit”.

For example, in VSCode it is possible to automatically format code on save.

Next up, let’s see some examples when you may want to split expressions into multiple lines.

How to Break a String into Multiple Lines

To break a string to multiple lines, wrap each string in the new line inbetween a pair of double quotation marks.

For instance, you can do this:

print( "This happens to be" " so long string that" " it may be a better idea" " to break the line not to" " extend it further to the right" )

But you cannot do this:

print( "This happens to be so long string that it may be a better idea to break the line not to extend it further to the right" )

Break a Function Arguments into Multiple Lines

If your function takes a number of arguments that extends line of code far to the right, feel free to break the expression into multiple lines.

For example, instead of doing this:

def example_function(first_number, second_number, third_number, fourth_number, fifth_number): pass
def example_function( first_number, second_number, third_number, fourth_number, fifth_number ): pass

Break a List into Multiple Lines

For example, let’s create a 3×3 matrix using a list:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

This is fine, but as you may know, a matrix is written in a table format. This makes it look more like a table of values.

To follow this convention in Python, you can split the matrix (the list of lists) into multiple lines:

matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]

Break a Dictionary into Multiple Lines

Just like breaking a list declaration into multiple lines, you can do it with a dictionary.

For instance, instead of a long expression like this:

Let’s split the dictionary into a bunch of lines to make it more understandable:

Break Mathematical Operations into Multiple Lines

To split a chain of binary operations, break the line before the operator. This makes the code more readable as the binary operators are not all over the place.

For example, instead of doing this:

income = gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest
income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest)

This example is directly from the PEP-0008 style guide.

Break Comparisons into Multiple Lines

Like any other expression, comparisons can also take some space. To avoid too long chains of comparisons, you can break the line.

if (is_rainy == True and is_hot == True and is_sunny == True and is_night == True): print("How is that possible. ")

Conclusion

Python’s implicit continuation makes it possible to break long expressions into multi-line expressions. This is useful for code readability.

To break an expression into multiple lines, wrap the expression around a set of parenthesis and break it down as you want.

If the expression is already in a set of parenthesis, square brackets, or curly braces, you can split it to multiple lines. This is true for example for lists, tuples, and dictionaries.

Thanks for reading. I hope you like it.

Источник

Перенос длинного кода на новую строку Python

Изображение баннера

Если строка превышает 80 символов в длину — по PEP 8 её нужно разделить на несколько.

Пример

Пример слишком длинной строки

url = your_base_url + «/monitor-service/api/v1/components/744618a0-78c5-4e19-78f4-6d215bde64a5»

Чтобы сделать перенос строки — воспользуйтесь символом \

url = your_base_url + \ «/monitor-service/api/v1/components/744618a0-78c5-4e19-78f4-6d215bde64a5»

url = your_base_url + «/monitor-service/api/v1/components/» \ «744618a0-78c5-4e19-78f4-6d215bde64a5»

f-string

Если нужно перенести f-string , например:

print ( f’ \n\n POST to < your_url >response status code is < response.status_code >\n ‘ )

Новую строку тоже нужно начать с f

print ( f’ \n\n POST to < your_url >response status code is ‘ f’ < response.status_code >\n ‘ )

Перенос при присваивании

Если нужно перенести выражение вида a = b, где b это что-то длинное:

# Правильно: # Выравнивание по открывающей скобке. foo = long_function_name(var_one, var_two, var_three, var_four) # Второй вариант так называемый «Подвешенный» отступ. foo = long_function_name ( var_one, var_two, var_three, var_four ) # Если поставить запятую в конце — закрывающую скобку можно. # поместить под первым непустым символом. result = some_function_that_takes_arguments ( ‘a’ , ‘b’ , ‘c’ , ‘d’ , ‘e’ , ‘f’ , ) # Либо в начало строки. result = some_function_that_takes_arguments ( ‘a’ , ‘b’ , ‘c’ , ‘d’ , ‘e’ , ‘f’ , ) # Неправильно: # Запрещено перечислять аргументы в первой строке # если следующая не выровнена. foo = long_function_name(var_one, var_two, var_three, var_four)

Объявление функций

Если нужно объявить функцию с большим числом параметров:

# Правильно: # Нужно отступить на 4 пробела, чтобы выделить параметры. def long_function_name ( var_one, var_two, var_three, var_four): print (var_one) # Неправильно # Параметры не выделяются и читать неудобно def long_function_name ( var_one, var_two, var_three, var_four): print (var_one)

if

Ветвления на основе if разрешено оформлять следующими способами:

# Без отступа. if (this_is_one_thing and that_is_another_thing): do_something() # Хороший приём — добавить комментарий, который улучшит читаемость # в редакторах с подсветкой синтаксиса. if (this_is_one_thing and that_is_another_thing): # Since both conditions are true, we can frobnicate. do_something() # Разрешено добавить отступ перед and. if (this_is_one_thing and that_is_another_thing): do_something()

Объявление списков

Списки можно объявлять двумя способами:

my_list = [ 1 , 2 , 3 , 4 , 5 , 6 , ] my_list = [ 1 , 2 , 3 , 4 , 5 , 6 , ]

Источник

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